C++ Classes & Objects

Classes

It is a user-defined data type and represents the blueprint from which objects are created. Further, it represents the set of properties or methods that are common to all objects of one type. A class never has any physical existence. It is a logical thing.

Syntax

class ClassName{

};

Let us take a real-time example, Cars. So many cars are available with different names but all are having some common properties like four wheels, speed, mileage, etc.

Here, Car is a ClassName and their properties are wheels, speed, mileage, etc.

Example

class Cars{

};

Objects

It is a basic unit of Object-Oriented Programming. It represents real-life entities.

An Object consists of:

State

It is represented by attributes of an object. It also reflects the properties of an object

Behaviour

It is represented by methods of an object. It also reflects the response of an object with other objects.

Identity

It gives a unique name to an object and enables one object to interact with other objects.

An object is an instance of a class. Each object is associated with its own memory area.

An object is created as,

classname obj1, obj2,……..

The members of the Class are also known as instance members since each instance has its own copy of those members.

When a member is accessed as,

obj1.AccType=’savings’;

It is an instruction to the compiler to assign ‘savings’ to the copy of AccType which belongs to the object obj1, i.e. ‘savings is assigned the memory area of obj1. The Dot Operator(.) is used to access a class member.

Program for Classes and Objects in C++

 

#include <bits/stdc++.h> 
using namespace std; 
class Dog                              //Dog is the ClassName

    // Access specifier 
    public:   
    // Data Members 
    string dogname;   
    // Member Functions() 
    void printname() 
    { 
       cout << "Dog name is: " << dogname; 
    } 
};   
int main() {   
    // Declare an object of the class dog
    Dog obj1;   
    // accessing data member 
    obj1.dogname = "Tommy";   
    // accessing member function 
    obj1.printname(); 
    return 0; 
} 

Output

Dog name is: Tommy

Leave a Comment

Your email address will not be published. Required fields are marked *