Classes and objects are the two main aspects of Object-Oriented Programming (OOP).
To understand them, think about a real-world example: a Car.
When the individual objects are created, they inherit all the variables and functions from the class.
In C++, you create a class using the class keyword, followed by the name of the class. It is standard convention to capitalize the first letter of a class name.
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
class MyClass: This defines the class named MyClass.public:: This is an access specifier. It means that the attributes and methods defined below it can be accessed from outside the class. myNum and myString are properties of the class.(Note: Don't forget the semicolon ; at the end of the class definition!)
Once a class is defined, you can create objects from it. To create an object of MyClass, specify the class name, followed by the object name.
To access the class attributes (myNum and myString), use the dot syntax (.) on the object:
#include <iostream> #include <string> using namespace std;class MyClass { public: int myNum; string myString; };
int main() { MyClass myObj; // Create an object of MyClass
// Access attributes and set values myObj.myNum = 15; myObj.myString = "Some text";
// Print attribute values cout << myObj.myNum << "\n"; cout << myObj.myString << "\n"; return 0; }
What is the correct syntax to create an object named "myCar" from a class named "Car"?