PREV NEXT
C++ Objects and Classes:
What is class in C++?
- As C++ is a multi-paradigm programming language so, it supports different programming styles and it supports object oriented programming which helps us to divide the complex problems into smaller sets by creating objects.
- So, to understand the objects you should know about the class. A class is a blueprint for the object. It is a user defined data type which holds the data members and member functions of its own and can be accessed and used by creating the instance of the class.
- It does not define any data but I does define what the class name is and what the object of that class will consist, what operations can be performed on that object.
- The class definition starts with the keyword class followed by the class name and the class body that is enclosed by a pair of curly braces {}.
- The class definition must be followed either by a semicolon or a list of declarations.
What is an object?
The class provides the blueprint for the objects so; objects are created from within the class. The objects of a class are declared exactly with the same sort of declaration that we declare the variables of basic types.
How to access the data members?
The data members can be defined as public, private and protected but defining as public they can be accessed using the direct member access operator (.).
To understand the concept clearly let us have a look at the example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
#include <iostream> using namespace std; class Sum { public: int a; // data members of class Sum int b; }; int main() { Sum s1; // Declare s1 of type Sum Sum s2; // Declare s2 of type Sum int add = 0; // it will store the sum of two data members // s1 specification s1.a = 5; s1.b = 6; // s2 specification s2.a = 4; s2.b = 8; // addition of s1 add = s1.a + s1.b; cout << "Addition of s1 : " << add <<endl; // addition of s2 add = s2.a + s2.b; cout << "Addition of s2 : " << add <<endl; return 0; } |