Implementation
C++ is an object-oriented programming language.
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.
Create a Class
To create a class, use the class
keyword:
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
Example explained
The
class
keyword is used to create a class calledMyClass
.The
public
keyword is an access specifier, which specifies that members (attributes and methods) of the class are accessible from outside the class. Take a look at this access specifiers.Inside the class, there is an integer variable
myNum
and a string variablemyString
. When variables are declared within a class, they are called attributes.At last, end the class definition with a semicolon
;
Class Methods
Methods are functions that belongs to the class.
There are two ways to define functions that belongs to a class:
Inside class definition
Outside class definition
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 (.
):
Last updated
Was this helpful?