Introduction
Real-world modeling helps us turn things we see around us into code. It makes programs easier to understand and work with.
Real-world modeling helps us turn things we see around us into code. It makes programs easier to understand and work with.
class ClassName { public: // attributes (data members) Type attribute1; Type attribute2; // methods (functions) void methodName() { // code } };
#include <string> using namespace std; class Person { public: string name; int age; };
#include <iostream> using namespace std; class Car { public: string brand; string color; int speed; void honk() { cout << "Beep beep!" << endl; } };
This program creates a Person named Alice who is 30 years old and then introduces her by printing a message.
#include <iostream> #include <string> using namespace std; class Person { public: string name; int age; void introduce() { cout << "Hi, I am " << name << " and I am " << age << " years old." << endl; } }; int main() { Person friend1; friend1.name = "Alice"; friend1.age = 30; friend1.introduce(); return 0; }
Remember to use public: to allow access to attributes and methods from outside the class.
Classes help organize code by grouping related data and actions together.
Real-world modeling uses classes to represent things and their behaviors.
Attributes hold information, methods perform actions.
This makes programs clearer and easier to manage.
Car in C++?class, followed by the class name and braces.class Car { }; which is correct. Others have syntax errors.class Dog {
public:
int age;
void bark() { std::cout << "Woof!"; }
};
int main() {
Dog myDog;
myDog.age = 5;
std::cout << myDog.age << " ";
myDog.bark();
return 0;
}myDog.age followed by a space, then calls bark() which prints "Woof!".5 plus Woof!, so result is "5 Woof!".class Book {
string title;
int pages;
public:
void setTitle(string t) { title = t; }
void setPages(int p) { pages = p; }
};string without std:: or using namespace std;.string is in the std namespace, so std::string is needed unless using directive is present.Library that holds many Book objects. Which design best represents this real-world relationship in C++?std::vector<Book> to hold multiple books, matching the real-world model.Pass the test and this pattern moves unknown