DEV Community

Pushpender Singh
Pushpender Singh

Posted on

C++ - Objects & Classes

Class

  1. Class is a user defined datatype.
  2. It contains variables and functions.
  3. It is used to create Objects.

Think of it like a blueprint.

Object

  1. It is instance of a class.
  2. One class can create as many objects.
  3. It represents real world entity.
  4. 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:-

  1. https://www.geeksforgeeks.org/c-classes-and-objects/
  2. https://amzn.to/2PBRuZ6

That's it guys.

If you find anything incorrect or know more about it let me know in the comments.

Top comments (0)