C++ is a multi-paradigm programming language. Meaning, it supports different programming styles.
One of the popular ways to solve a programming problem is by creating objects, known as object-oriented style of programming.
C++ supports object-oriented (OO) style of programming which allows you to divide complex problems into smaller sets by creating objects.
Object is simply a collection of data and functions that act on those data.
C++ Class
Before you create an object in C++, you need to define a class.
A class is a blueprint for the object.
We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object.
As, many houses can be made from the same description, we can create many objects from a class.
How to define a class in C++?
A class is defined in C++ using keyword
class
followed by the name of class.
The body of class is defined inside the curly brackets and terminated by a semicolon at the end.
class className{// some functions// some data};
Example: Class in C++
class Test
{private:int data1;float data2;public:void function1(){ data1 = 2; }float function2(){data2 = 3.5;return data2;}};
Here, we defined a class named Test
.
This class has two data members: data1 and data2 and two member functions: function1() and function2().
Keywords: private and public
You may have noticed two keywords: private and public in the above example.
The private keyword makes data and functions private. Private data and functions can be accessed only from inside the same class.
The public keyword makes data and functions public. Public data and functions can be accessed out of the class.
Here, data1 and data2 are private members where as function1() and function2() are public members.
If you try to access private data from outside of the class, compiler throws error. This feature in OOP is known as data hiding.