C++ Classes and Objects

C++ Classes and Objects

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.


1. Creating a 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)
};

(Note: Don't forget the semicolon ; at the end of the class definition!)


2. Creating an Object

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:

Creating an Object Example

#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; }


Exercise

?

What is the correct syntax to create an object named "myCar" from a class named "Car"?