C++ - Objects & Classes
Pushpender Singh
Posted on December 19, 2019
Class
- Class is a user defined datatype.
- It contains variables and functions.
- It is used to create Objects.
Think of it like a blueprint.
Object
- It is instance of a class.
- One class can create as many objects.
- It represents real world entity.
- sometime called instance variable.
Analogy
Let's you are an architect and you designed a blueprint of a house. Your designed blueprint is amazing that so many people want to make house out of it. So you show them your blueprint. Finally everyone have their dream houses. In this case your blueprint is called class and houses are called objects.
Some Formal Terms
Variable in Object = Member Data
Function in Object = Member Function
(Note:- some programming languages, member functions called methods.)
How to define class?
class className {
private:
// Member Data
int a;
public:
// Member Function
void showdata() {
std::cout << a << std::endl;
}
};
// private and public are called access modifiers.
How to create Object?
className objectName;
Calling Member Function
objectName.showdata();
/* Here "dot" in between object and member function
called "class member access operator".
*/
Constructor
A Constructor is a member function that is executed automatically whenever an object is created.
How to define a Constructor?
class className {
public:
classname() {
// constructor body
}
};
/*
1. It must be same name as class name.
2. It have no return type.
*/
Destructor
A Destructor is a member function that is executed automatically whenever an object is destroyed.
How to define a Destructor?
class className {
public:
~classname() {
// Destructor body
}
};
/*
1. It must be same name as class name.
2. It have no return type.
*/
References:-
That's it guys.
If you find anything incorrect or know more about it let me know in the comments.
Posted on December 19, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.