C++ - Polymorphism
C++ is an object-oriented programming language and it allows us to create objects. To create an object, first of all, the object should be defined in the program which is done by creating a class. A class is a code template that is used to define a new object type. Within a class, the object's variables and functions are defined and when an object is created, its variables and functions are determined by the class in which it is created.
Create Class
To create a class in C++, class or struct keyword is used. It starts with the keyword followed by class name. See the syntax below:
Syntax
//defining a class class className { access_specifier1: member1; access_specifier2: member2; };
access_specifier: It defines the access type of the members and functions of the class. There are three types of access specifier in C++.
- public: members are accessible from outside the class.
- protected: members are not accessible from outside the class but accessible in friend and inherited classes.
- private: members are not accessible from outside the class but accessible in friend classes.
Create Object
To create an object, specify the class name followed by object name. To access the class's members, dot (.) syntax is used. See the syntax below:
Syntax
//creating an object className objectName; //access class member objectName.member1
Example:
In the example below, a class (new object type) called Circle and object called MyCircle of the same class are created in the main() function. MyCircle object has only one integer public member radius which is accessed in the main function using dot (.) syntax.
#include <iostream> using namespace std; class Circle { public: int radius = 10; }; int main () { Circle MyCircle; cout<<MyCircle.radius; return 0; }
The output of the above code will be:
10
Class Functions
Class function also known as class method can be defined in two ways.
- Inside class definition
- Outside class definition
Example: Class function defined inside class
In the example below, a class function called area is defined inside the class Circle. A class function can be accessed in the same way as other class members, using dot (.) syntax.
#include <iostream> using namespace std; class Circle { public: int radius = 10; void area() { float x; x = 22/7.0*radius*radius; cout<<x; } }; int main (){ Circle MyCircle; MyCircle.area(); return 0; }
The output of the above code will be:
314.286
Example: Class function defined outside class
To define a class function outside the class, scope operator (::) is used. It starts with class name followed by scope operator and function name. Along with this, the function must be declared inside the class as shown in the example below.
#include <iostream> using namespace std; class Circle { public: int radius = 10; void area(); }; void Circle::area() { float x; x = 22/7.0*radius*radius; cout<<x; } int main () { Circle MyCircle; MyCircle.area(); return 0; }
The output of the above code will be:
314.286