Understanding C++ Classes and Objects
C++ Classes and Objects Introduction to C++ Classes and Objects C++ is a widely used object oriented programming language. In C++, everything revolves around classes and objects...
C++ Classes and Objects
Introduction to C++ Classes and Objects
C++ is a widely-used object-oriented programming language. In C++, everything revolves around classes and objects, which contain attributes and methods. Consider a car as a real-world example of an object. A car has attributes like weight and color, and methods such as driving and braking. In programming terms, attributes are variables and methods are functions that belong to the class, collectively known as "class members". A class acts as a user-defined data type and serves as a "blueprint" for creating objects.
Creating a Class
To define a class in C++, the class keyword is used. Here’s an example explaining the concept:
class MyClass {
public:
int myNum;
std::string myString;
};
Example Explained
- The
classkeyword initiates the creation of a class namedMyClass. - The
publickeyword is an access specifier that allows the class members (attributes and methods) to be accessible from outside the class. More details on access specifiers will be covered later. - Within the class, there are two variables:
myNum(an integer) andmyString(a string). These variables are referred to as attributes. - The class definition concludes with a semicolon
;.
Creating an Object
In C++, objects are instantiated from classes. Once a class like MyClass is defined, objects can be created from it. To create an object of MyClass, specify the class name followed by the object name. Access the class attributes using the dot syntax (.) with the object:
MyClass myObj;
myObj.myNum = 15;
myObj.myString = "Hello";
Multiple Objects
It is possible to create multiple objects from a single class in C++. Here’s how:
MyClass obj1;
MyClass obj2;
Each object, obj1 and obj2, will have its own copy of the class attributes.