Class Objects
Class Objects
Everything in C++ is associated with classes and objects, along with its attributes and methods.
For example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake. Attributes and methods are
basically variables and functions that belongs to the class. These are often referred to as "class
members".
A class is a user-defined data type that we can use in our program, and it works as an object
constructor, or a "blueprint" for creating objects.
Example
Example explained
Create an Object
• In C++, an object is created from a class. We have already created the class
named MyClass, so now we can use this to create objects.
• 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:
int main() {
MyClass myObj; // Create an object of MyClass
Example
// Create a Car class with some attributes
class Car {
public:
string brand;
string model;
int year;
};
int main() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
Class Methods
In the following example, we define a function inside the class, and we name it "myMethod".
Note: You access methods just like you access attributes; by creating an object of the class and
using the dot syntax (.):
Inside Example
class MyClass { // The class
public: // Access specifier
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
To define a function outside the class definition, you have to declare it inside the class and then
define it outside of the class. This is done by specifying the name of the class, followed the scope
resolution :: operator, followed by the name of the function:
class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Constructors
A constructor in C++ is a special method that is automatically called when an object of a class is
created. To create a constructor, use the same name as the class, followed by parentheses ():