Implementation
C++ is an object-oriented programming language.
Last updated
Was this helpful?
C++ is an object-oriented programming language.
Last updated
Was this helpful?
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.
To create a class, use the class
keyword:
The class
keyword is used to create a class called MyClass
.
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 .
Inside the class, there is an integer variable myNum
and a string variable myString
. When variables are declared within a class, they are called attributes.
At last, end the class definition with a semicolon ;
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 (.
):