Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Monday, September 14, 2026

September 14, 2026

Arrays of Objects, Pointers to Objects, Type Checking, this Pointer

 

The Dynamic Allocation Operators: Arrays of Objects, Pointers to Objects, Type Checking, this Pointer

Dynamic memory allocation is an important feature of C++ that allows memory to be allocated during program execution rather than being fixed completely at compile time. This is particularly useful in object-oriented programming when the number of objects required by a program is known only at runtime.

C++ provides two important operators for dynamic memory management:

  • new — allocates memory dynamically.

  • delete — releases dynamically allocated memory.

For arrays, C++ provides:

  • new[] — dynamically allocates an array.

  • delete[] — releases a dynamically allocated array.

Dynamic allocation becomes especially useful when working with arrays of objects, pointers to objects, and dynamically created objects.


1. Dynamic Allocation Operators

In C++, memory can be allocated dynamically using the new operator.

Syntax

pointer = new data_type;

For example:

int *p;

p = new int;

The new operator allocates memory for an integer and returns the address of that memory location.

A value can then be assigned using the pointer:

*p = 50;

The memory should eventually be released using delete:

delete p;

The basic process can be represented as:

Image

Image

Image

Image

Image

Image

              Program
                 |
              new int
                 |
                 ↓
          Dynamic Memory
              (Heap)
                 |
             ┌───────┐
             │  50   │
             └───────┘
                 ↑
                 |
                 p

Here, p stores the address of the dynamically allocated integer.


2. new Operator

The new operator performs dynamic memory allocation and returns a pointer to the allocated object.

For example:

int *p = new int;

The statement performs two operations:

  1. Memory is allocated for an int.

  2. The address of the allocated memory is stored in p.

A value can be assigned as:

*p = 100;

Complete Example

#include <iostream>
using namespace std;

int main()
{
    int *p = new int;

    *p = 100;

    cout << "Value = " << *p << endl;

    delete p;

    return 0;
}

Output

Value = 100

3. delete Operator

The delete operator releases memory that was previously allocated using new.

Syntax

delete pointer;

Example:

int *p = new int;

*p = 50;

delete p;

After the memory has been released, the pointer should not be dereferenced.

A useful practice is to make the pointer null after deletion:

delete p;
p = nullptr;

This helps avoid accidentally using a pointer that no longer refers to a valid dynamically allocated object.


4. Dynamic Allocation of Objects

The new operator can also dynamically create an object.

Suppose we have:

class Student
{
public:
    void display()
    {
        cout << "Student object";
    }
};

An object can be dynamically created using:

Student *ptr = new Student;

Here:

  • Student is the class.

  • ptr is a pointer to a Student.

  • new Student dynamically creates a Student object.

The member function can be accessed using the arrow (->) operator:

ptr->display();

The object is released using:

delete ptr;

5. Example: Pointer to a Dynamically Allocated Object

#include <iostream>
using namespace std;

class Student
{
public:
    int rollNo;

    void display()
    {
        cout << "Roll Number: " << rollNo << endl;
    }
};

int main()
{
    Student *ptr = new Student;

    ptr->rollNo = 101;
    ptr->display();

    delete ptr;

    return 0;
}

Output

Roll Number: 101

The statement:

Student *ptr = new Student;

creates the object dynamically.

The statement:

ptr->display();

calls the member function through the pointer.


6. Arrays of Objects

In object-oriented programming, it is often necessary to create multiple objects of the same class.

For example, a university may need to store information about 100 students.

Instead of creating individual objects:

Student s1, s2, s3, ...;

an array of objects can be created:

Student students[100];

An array of objects stores multiple objects of the same class in a contiguous sequence of elements, subject to the usual object and array rules.


7. Example of Array of Objects

#include <iostream>
using namespace std;

class Student
{
public:
    int rollNo;

    void display()
    {
        cout << "Roll Number: " << rollNo << endl;
    }
};

int main()
{
    Student s[3];

    s[0].rollNo = 101;
    s[1].rollNo = 102;
    s[2].rollNo = 103;

    s[0].display();
    s[1].display();
    s[2].display();

    return 0;
}

Output

Roll Number: 101
Roll Number: 102
Roll Number: 103

The array can be visualized as:

Image

Image

Image

Image

Image

Student s[3]

┌─────────────┬─────────────┬─────────────┐
│   s[0]      │   s[1]      │   s[2]      │
│ Roll = 101  │ Roll = 102  │ Roll = 103  │
└─────────────┴─────────────┴─────────────┘

Each array element is a separate object of the Student class.


8. Dynamically Allocated Array of Objects

An array of objects can also be created dynamically using new[].

Syntax

ClassName *pointer = new ClassName[size];

For example:

Student *students = new Student[5];

This dynamically allocates an array containing five Student objects.

The dynamically allocated array must be released using delete[]:

delete[] students;

It is important to use delete[] for memory allocated with new[].


9. Example: Dynamic Array of Objects

#include <iostream>
using namespace std;

class Student
{
public:
    int rollNo;

    void display()
    {
        cout << "Roll Number: " << rollNo << endl;
    }
};

int main()
{
    Student *students = new Student[3];

    students[0].rollNo = 101;
    students[1].rollNo = 102;
    students[2].rollNo = 103;

    for (int i = 0; i < 3; i++)
    {
        students[i].display();
    }

    delete[] students;

    return 0;
}

Output

Roll Number: 101
Roll Number: 102
Roll Number: 103

The memory arrangement can be understood as:

                students
                    |
                    ↓
        Dynamic Memory (Heap)
        ┌────────┬────────┬────────┐
        │Student │Student │Student │
        │  [0]   │  [1]   │  [2]   │
        └────────┴────────┴────────┘
                    |
                 delete[]

10. Constructors with Dynamic Arrays of Objects

When objects are dynamically allocated using new, their constructors are automatically invoked.

Consider:

class Student
{
public:
    Student()
    {
        cout << "Constructor called" << endl;
    }
};

Now:

Student *s = new Student[3];

causes the constructor to execute for each of the three objects.

Similarly:

delete[] s;

causes the destructor to execute for each object, in the appropriate destruction order.

This is one of the important advantages of C++ object-oriented memory management.


11. Pointers to Objects

A pointer that stores the address of an object is called a pointer to an object.

Syntax

ClassName *pointer;

Example:

Student *ptr;

An object can be associated with the pointer:

Student s;

ptr = &s;

Now ptr points to object s.


12. Accessing Object Members Through a Pointer

There are two ways to access a member through an object pointer.

Using (*pointer).member

(*ptr).display();

Using the arrow operator ->

ptr->display();

Both represent the same member access.

For example:

ptr->rollNo

is equivalent to:

(*ptr).rollNo

The arrow operator is generally more convenient and readable.


13. Example: Pointer to Object

#include <iostream>
using namespace std;

class Employee
{
public:
    int id;

    void display()
    {
        cout << "Employee ID: " << id << endl;
    }
};

int main()
{
    Employee e;

    Employee *ptr = &e;

    ptr->id = 501;
    ptr->display();

    return 0;
}

Output

Employee ID: 501

Here:

Employee *ptr = &e;

makes ptr point to the object e.

Then:

ptr->id = 501;

accesses the id member through the pointer.


14. Object Pointer vs Normal Object

Consider:

Student s;

Here s is an object.

Now:

Student *ptr = &s;

Here ptr is a pointer to the object.

The distinction is:

ObjectObject Pointer
Student s;Student *ptr;
Represents an objectStores address of an object
Access member using .Access member using ->
s.display()ptr->display()

15. Pointer to Dynamically Created Object

A pointer can directly receive the address returned by new.

Student *ptr = new Student;

This is a very common pattern in C++.

The relationship is:

        ptr
         |
         | stores address
         ↓
   ┌─────────────┐
   │   Student   │
   │    Object   │
   └─────────────┘
      Dynamic
      Memory

The object can be accessed using:

ptr->display();

and released using:

delete ptr;

16. Type Checking

Type checking is the process of ensuring that an expression, object, pointer, or operation is used with a compatible data type.

C++ is a statically typed language, which means that types are primarily determined and checked at compile time.

For example:

int x = 10;

Here, x is declared as an int.

The compiler can detect invalid assignments such as:

x = "Hello";

because a string literal cannot be assigned directly to an int.

Type checking helps detect programming errors before the program executes.


17. Type Checking with Pointers and Objects

Type compatibility is particularly important when pointers are used.

For example:

class A
{
};

class B
{
};

A *p;
B *q;

The pointer p is intended to point to an object of type A, whereas q is intended to point to an object of type B.

An unrelated pointer conversion is not normally permitted without an explicit cast.

This provides a degree of compile-time safety.


18. Run-Time Type Information

C++ also provides Run-Time Type Information (RTTI) for determining the type of an object during program execution.

Two important mechanisms associated with RTTI are:

  • dynamic_cast

  • typeid

These are particularly useful when working with inheritance and polymorphism.


19. typeid Operator

The typeid operator can be used to obtain information about the type of an expression.

It requires:

#include <typeinfo>

Example:

#include <iostream>
#include <typeinfo>
using namespace std;

int main()
{
    int x = 10;

    cout << typeid(x).name();

    return 0;
}

The exact text returned by name() is implementation-dependent, so students should not assume that a particular compiler must print the same type code.


20. typeid with Classes

Consider:

#include <iostream>
#include <typeinfo>
using namespace std;

class Student
{
};

int main()
{
    Student s;

    cout << typeid(s).name();

    return 0;
}

typeid(s) provides a std::type_info object describing the type of s.

The exact representation returned by:

typeid(s).name()

depends on the compiler and implementation.

Therefore, typeid is useful for type identification, but name() should not generally be used when portable, human-readable type names are required.


21. dynamic_cast

dynamic_cast is mainly used with polymorphic class hierarchies to perform checked conversions at runtime.

Consider:

class Animal
{
public:
    virtual ~Animal() = default;
};

class Dog : public Animal
{
public:
    void bark()
    {
        cout << "Dog barks";
    }
};

Now:

Animal *ptr = new Dog;

Dog *dogPtr = dynamic_cast<Dog*>(ptr);

If ptr actually points to a Dog object, the conversion succeeds.

If it does not, a pointer dynamic_cast returns nullptr.

Example:

if (dogPtr != nullptr)
{
    dogPtr->bark();
}

This provides a runtime-checked downcast.


22. Why Type Checking Is Important

Type checking helps:

  • Detect incompatible operations.

  • Prevent many programming errors.

  • Improve program reliability.

  • Provide safer pointer conversions.

  • Support runtime type identification in polymorphic hierarchies.

  • Make object-oriented programs easier to maintain.


23. this Pointer

The this pointer is a special pointer available inside a non-static member function.

It points to the current object on which the member function is operating.

For example:

class Student
{
public:
    void display()
    {
        cout << this;
    }
};

When:

Student s;
s.display();

is executed, this refers to s.

Conceptually:

Image

Image

Image

                Object s
             ┌─────────────┐
             │ rollNo      │
             │ marks       │
             └─────────────┘
                    ↑
                    |
                this pointer
                    |
             member function

Thus, this provides the member function with a way to refer to the object that invoked it.


24. Example of this Pointer

#include <iostream>
using namespace std;

class Student
{
private:
    int rollNo;

public:
    void setRollNo(int rollNo)
    {
        this->rollNo = rollNo;
    }

    void display()
    {
        cout << "Roll Number: " << this->rollNo;
    }
};

int main()
{
    Student s;

    s.setRollNo(101);
    s.display();

    return 0;
}

Output

Roll Number: 101

25. Why this Is Required in the Above Example

The function has a parameter named rollNo:

void setRollNo(int rollNo)

The class also has a data member named rollNo:

int rollNo;

Inside the function:

this->rollNo = rollNo;

means:

this->rollNo    → data member of current object
rollNo          → function parameter

Therefore, the statement assigns the parameter value to the current object's data member.

Without this, the two names would refer to the parameter in that scope.


26. this Pointer with Multiple Objects

The same member function can be called by different objects.

Student s1;
Student s2;

s1.display();
s2.display();

When s1 calls the function, this refers to s1.

When s2 calls the function, this refers to s2.

Conceptually:

s1.display()                 s2.display()
      |                            |
      ↓                            ↓
 this → s1                    this → s2

Therefore, this allows the same member-function code to operate on the correct current object.


27. Returning the Current Object Using this

The this pointer can also be used to return the current object from a member function.

A common form is:

return *this;

For example:

class Number
{
private:
    int value;

public:
    Number& setValue(int value)
    {
        this->value = value;
        return *this;
    }

    void display()
    {
        cout << value;
    }
};

Now:

Number n;

n.setValue(10).display();

The setValue() function returns the current object by reference, allowing another member function to be called immediately.


28. Important Properties of this Pointer

The this pointer:

  1. Is available inside non-static member functions.

  2. Points to the current object.

  3. Helps distinguish data members from parameters/local variables with the same name.

  4. Can be used to access current object's members.

  5. Can be used to return the current object using *this.

  6. Is not available in a static member function because a static member function is not associated with a particular object.

  7. Its type depends on the class and the cv/ref qualification of the member function.


29. new, delete, new[] and delete[]

These operators should be clearly distinguished.

OperatorPurpose
newAllocates one object
deleteReleases one object allocated with new
new[]Allocates an array of objects/elements
delete[]Releases an array allocated with new[]

Correct pairing is important:

Student *p = new Student;
delete p;

and:

Student *p = new Student[10];
delete[] p;

Do not replace:

delete[] p;

with:

delete p;

when the memory was allocated using new[].


30. Complete Example Combining the Concepts

#include <iostream>
using namespace std;

class Student
{
private:
    int rollNo;

public:
    Student()
    {
        rollNo = 0;
    }

    void setRollNo(int rollNo)
    {
        this->rollNo = rollNo;
    }

    void display()
    {
        cout << "Roll Number: " << this->rollNo << endl;
    }
};

int main()
{
    Student *students = new Student[3];

    students[0].setRollNo(101);
    students[1].setRollNo(102);
    students[2].setRollNo(103);

    for (int i = 0; i < 3; i++)
    {
        students[i].display();
    }

    delete[] students;

    return 0;
}

Output

Roll Number: 101
Roll Number: 102
Roll Number: 103

This single example demonstrates:

  • Class

  • Objects

  • Dynamic allocation

  • Array of objects

  • Object pointers

  • new[]

  • delete[]

  • Member-function calls

  • this pointer


31. Common Errors

Error 1: Using delete instead of delete[]

Student *s = new Student[5];

delete s;       // Incorrect

Correct:

delete[] s;

Error 2: Dereferencing a deleted pointer

Student *s = new Student;

delete s;

s->display();   // Invalid

After deletion, the pointer no longer points to a valid object.

A useful practice is:

delete s;
s = nullptr;

Error 3: Accessing object members using the wrong operator

For an object:

Student s;

s.display();

For a pointer:

Student *p = &s;

p->display();

Error 4: Confusing the object with its pointer

Student s;
Student *p = &s;

Here:

  • s is the object.

  • p is the pointer to the object.


32. Summary

Dynamic allocation allows C++ programs to create objects and arrays whose lifetime and size are determined during execution. The new operator dynamically creates an object or array and returns its address, while delete and delete[] release the corresponding memory.

An array of objects allows multiple instances of the same class to be stored and processed systematically. When the size of the array is known only during execution, a dynamic array can be created using new[] and released using delete[].

A pointer to an object stores the address of an object and allows its members to be accessed using the arrow (->) operator. C++ also provides type checking and RTTI mechanisms, including typeid and dynamic_cast, which are particularly useful when dealing with polymorphic class hierarchies.

The this pointer represents the current object inside a non-static member function. It is particularly useful when a parameter has the same name as a data member and when a member function needs to return the current object.

Quick Revision

Dynamic Memory Allocation
          |
    ----------------
    |              |
   new            delete
    |              |
    ↓              ↓
Object/Array    Release memory
    |
    ├── new Object
    │      ↓
    │   Object Pointer
    │
    └── new[]
           ↓
     Array of Objects
           |
        delete[]
           
Type Checking
     |
     ├── Compile-time type checking
     └── RTTI
          ├── typeid
          └── dynamic_cast

this Pointer
     ↓
Current Object

Core concepts to remember:

new → dynamically create
delete → dynamically destroy one object
new[] → dynamically create an array
delete[] → destroy a dynamically allocated array
-> → access members through an object pointer
typeid → obtain runtime type information
dynamic_cast → checked runtime cast in polymorphic hierarchies
this → pointer to the current object

September 14, 2026

Introduction to C++: Classes and Objects, Structures and Classes, Unions and Classes

 

Introduction to C++: Classes and Objects, Structures and Classes, Unions and Classes

1. Introduction to C++

C++ is a general-purpose, compiled programming language developed by Bjarne Stroustrup at Bell Labs. It was originally developed as an extension of the C programming language with support for object-oriented programming features.

C++ supports multiple programming paradigms, including:

  • Procedural programming

  • Object-oriented programming

  • Generic programming

  • Functional programming features

For object-oriented programming, C++ provides important concepts such as classes, objects, encapsulation, inheritance, polymorphism, abstraction, constructors and destructors.

The fundamental difference between procedural and object-oriented programming is that procedural programming primarily organizes a program around functions and procedures, whereas object-oriented programming organizes the program around objects that combine data and behaviour.


2. Classes and Objects

Classes and objects are the fundamental building blocks of object-oriented programming in C++.

A class defines the structure and behaviour of a particular type of object, whereas an object is an instance of that class.

For example, if Student is a class, then s1, s2, and s3 can be objects of the Student class.

                 Class
              Student
                  |
        ---------------------
        |         |         |
       s1        s2        s3
     Object    Object    Object

A class can contain:

  • Data members

  • Member functions

  • Constructors

  • Destructors

  • Access specifiers

  • Other nested declarations


2.1 Class

A class is a user-defined data type that combines related data and functions into a single unit.

Definition

A class is a user-defined data type that encapsulates data members and member functions and provides a blueprint for creating objects.

Syntax

class ClassName
{
private:
    // data members

public:
    // member functions
};

For example:

class Student
{
private:
    int rollNo;
    float marks;

public:
    void display()
    {
        cout << rollNo << " " << marks;
    }
};

Here, Student is a class.


3. Object

An object is an instance of a class.

Once a class has been defined, objects can be created using the class name.

Syntax

ClassName objectName;

Example:

Student s1;

Here, s1 is an object of the Student class.

Multiple objects can be created:

Student s1, s2, s3;

Each object has its own state represented by its non-static data members.


4. Example of Class and Object

#include <iostream>
using namespace std;

class Student
{
public:
    int rollNo;
    float marks;

    void display()
    {
        cout << "Roll Number: " << rollNo << endl;
        cout << "Marks: " << marks << endl;
    }
};

int main()
{
    Student s1;

    s1.rollNo = 101;
    s1.marks = 85.5;

    s1.display();

    return 0;
}

Output

Roll Number: 101
Marks: 85.5

Explanation

The statement:

class Student

defines the class.

The statement:

Student s1;

creates an object named s1.

The members are accessed using the dot (.) operator:

s1.rollNo = 101;
s1.marks = 85.5;
s1.display();

Thus, an object provides access to the accessible members of its class.


5. Class and Object: Important Relationship

A class can be considered a blueprint or logical definition, while an object represents an actual instance created from that definition.

For example:

ClassObjects
Students1, s2, s3
Carcar1, car2
Employeee1, e2
BankAccountaccount1, account2

A single class can therefore be used to create multiple objects.

Image

Image

Image

Image

Image

Image


6. Structures and Classes

C++ provides both structures (struct) and classes (class) for creating user-defined data types.

Both can contain:

  • Data members

  • Member functions

  • Constructors

  • Destructors

  • Access specifiers

  • Static members

  • Nested types

  • Inheritance and other class-related features

Therefore, a C++ structure is considerably more powerful than the traditional C structure.

However, there is an important default-access difference between a struct and a class.


7. Structure in C++

A structure is declared using the struct keyword.

Syntax

struct StructureName
{
    data_members;
    member_functions;
};

Example:

struct Student
{
    int rollNo;
    float marks;

    void display()
    {
        cout << rollNo << " " << marks;
    }
};

An object can be created as:

Student s1;

The public data members can be accessed directly:

s1.rollNo = 101;
s1.marks = 85.5;

8. Structure Example

#include <iostream>
using namespace std;

struct Student
{
    int rollNo;
    float marks;

    void display()
    {
        cout << "Roll Number: " << rollNo << endl;
        cout << "Marks: " << marks << endl;
    }
};

int main()
{
    Student s;

    s.rollNo = 101;
    s.marks = 88.5;

    s.display();

    return 0;
}

Output

Roll Number: 101
Marks: 88.5

This demonstrates that a C++ struct can contain both data and functions.


9. Structure vs Class

The syntax of struct and class is very similar in C++.

The most important difference is their default member access.

Featurestructclass
Keywordstructclass
Default member accesspublicprivate
Default base-class accesspublicprivate
Member functionsSupportedSupported
ConstructorsSupportedSupported
DestructorsSupportedSupported
InheritanceSupportedSupported
PolymorphismSupportedSupported
EncapsulationSupportedSupported

For example:

struct A
{
    int x;
};

Here x is public by default.

Therefore:

A obj;
obj.x = 10;

is valid.

Now consider:

class B
{
    int x;
};

Here x is private by default.

Therefore:

B obj;
obj.x = 10;     // Error

10. Structure and Class Example

The following program demonstrates the difference:

#include <iostream>
using namespace std;

struct StudentStruct
{
    int rollNo;
};

class StudentClass
{
    int rollNo;
};

int main()
{
    StudentStruct s1;
    s1.rollNo = 101;       // Valid

    StudentClass s2;
    // s2.rollNo = 102;    // Error: private member

    cout << s1.rollNo;

    return 0;
}

The important point is not that a structure cannot provide encapsulation. In C++, it can. The distinction is mainly that its members are public by default, whereas class members are private by default.


11. When to Use Structure and Class?

In C++, the choice is generally a matter of design intent and convention, not capability alone.

A struct is often used when the type primarily represents a simple collection of related values and public access is appropriate.

Example:

struct Point
{
    int x;
    int y;
};

A class is generally preferred when the type represents an abstraction with controlled access to its internal state and associated behaviour.

Example:

class BankAccount
{
private:
    double balance;

public:
    void deposit(double amount);
    void withdraw(double amount);
};

Thus, class is commonly associated with encapsulation and abstraction, while struct is often used for simple data-oriented types.


12. Unions in C++

A union is a user-defined type in which all non-static data members share the same memory location.

Unlike a structure or class, where separate non-static data members generally have distinct storage, the members of a union overlap in storage.

Syntax

union UnionName
{
    data_member1;
    data_member2;
    data_member3;
};

Example:

union Data
{
    int i;
    float f;
    char ch;
};

Here, i, f, and ch share the same storage.


13. Memory Concept of a Union

Consider:

union Data
{
    int i;
    float f;
    char ch;
};

Conceptually:

          Same Memory Location
        ┌─────────────────────┐
        │                     │
        │    i     /   f      │
        │          /          │
        │        ch           │
        │                     │
        └─────────────────────┘

Only one member's stored value should generally be treated as the active member at a time, subject to the language rules.

The size of a union is sufficient to accommodate its largest member, with alignment requirements taken into account.


14. Union Example

#include <iostream>
using namespace std;

union Data
{
    int i;
    float f;
};

int main()
{
    Data d;

    d.i = 10;
    cout << "Integer: " << d.i << endl;

    d.f = 25.5;
    cout << "Float: " << d.f << endl;

    return 0;
}

Output

Integer: 10
Float: 25.5

When d.f is assigned after d.i, the storage is reused for the float. The previous int value should not be treated as simultaneously preserved as an independent value.


15. Union and Class

Like a class, a union in C++ can contain:

  • Data members

  • Member functions

  • Constructors

  • Destructors

  • Static members

  • Access specifiers

For example:

union Data
{
private:
    int value;

public:
    void setValue(int v)
    {
        value = v;
    }

    void display()
    {
        cout << value;
    }
};

Thus, a C++ union is not limited to the simple data-only structure commonly associated with unions in C.


16. Union vs Class

The important distinction is how their non-static data members are stored.

FeatureUnionClass
Keywordunionclass
Data membersShare storageNormally have separate storage
Simultaneous independent valuesGenerally not for overlapping membersYes
Default accesspublicprivate
Member functionsSupportedSupported
ConstructorsSupportedSupported
DestructorsSupportedSupported
InheritanceNot supportedSupported
Primary purposeMemory-efficient alternative representationEncapsulation and object-oriented design

17. Structure vs Union

The difference between a structure and a union is particularly important for understanding memory.

Consider:

struct Data
{
    int i;
    float f;
};

and:

union Data
{
    int i;
    float f;
};

In the structure, both members have their own storage.

Conceptually:

Structure

┌──────────────┐
│      i       │
├──────────────┤
│      f       │
└──────────────┘

In the union, the members overlap:

Union

┌──────────────┐
│ i / f        │
└──────────────┘

Therefore, structures are suitable when all member values need to coexist, whereas unions are useful when different representations share storage and only one active representation is required at a time.


18. Structures, Unions and Classes in C++

The three constructs can be compared as follows:

FeatureStructureUnionClass
Keywordstructunionclass
Default accessPublicPublicPrivate
Data membersSeparate storageShared storageSeparate storage
Member functionsYesYesYes
ConstructorsYesYes, subject to union restrictionsYes
DestructorsYesYes, subject to union restrictionsYes
InheritanceYesNoYes
PolymorphismYesNo inheritance-based polymorphismYes
EncapsulationSupportedSupportedStrongly supported by default
Typical useData-oriented typesAlternative representations/shared storageOOP abstractions

19. Important Concept: struct and class Are More Similar in C++ Than in C

Students coming from C often assume:

Structure = data only
Class = data + functions

This is not correct for C++.

In C++, a struct can have member functions, constructors, destructors, access specifiers and inheritance.

For example:

struct Rectangle
{
private:
    int length;
    int breadth;

public:
    Rectangle(int l, int b)
    {
        length = l;
        breadth = b;
    }

    int area()
    {
        return length * breadth;
    }
};

This is a valid C++ structure with private data, a constructor and a member function.

Therefore, the major language-level difference between struct and class is primarily their default access and default inheritance access, not simply whether they can contain functions.


20. Practical Example Combining Class, Structure and Union

The following example demonstrates the three concepts:

#include <iostream>
using namespace std;

struct Point
{
    int x;
    int y;
};

union Value
{
    int integerValue;
    float decimalValue;
};

class Rectangle
{
private:
    int length;
    int breadth;

public:
    void setData(int l, int b)
    {
        length = l;
        breadth = b;
    }

    int area()
    {
        return length * breadth;
    }
};

int main()
{
    Point p;
    p.x = 10;
    p.y = 20;

    Value v;
    v.integerValue = 100;

    Rectangle r;
    r.setData(10, 5);

    cout << "Point: (" << p.x << ", " << p.y << ")" << endl;
    cout << "Union value: " << v.integerValue << endl;
    cout << "Rectangle area: " << r.area() << endl;

    return 0;
}

Output

Point: (10, 20)
Union value: 100
Rectangle area: 50

This example demonstrates three different design purposes:

  • Point uses a structure for a simple collection of related values.

  • Value uses a union where alternative values share storage.

  • Rectangle uses a class to encapsulate data and behaviour.


21. Key Points to Remember

  1. C++ supports both procedural and object-oriented programming.

  2. A class is a user-defined type that combines data and behaviour.

  3. An object is an instance of a class.

  4. The dot (.) operator is generally used to access accessible members through an object.

  5. A C++ struct can contain both data members and member functions.

  6. The default access level of a struct is public.

  7. The default access level of a class is private.

  8. A union stores its non-static data members in overlapping storage.

  9. A union is useful when different representations need to use the same storage.

  10. C++ unions can contain member functions and other class-like features, but they do not support inheritance.

  11. A class is generally preferred when designing an abstraction requiring controlled access to its internal state.

  12. struct and class in C++ are much more similar than their C counterparts.

  13. The major default-access distinction is:

struct → public

class → private

  1. The main memory distinction is:

structure/class → members generally have separate storage

union → members share storage


Quick Revision

C++
 |
 ├── Class
 │    ├── Data Members
 │    ├── Member Functions
 │    └── Objects
 │
 ├── Structure
 │    ├── Data Members
 │    ├── Member Functions
 │    └── Public by default
 │
 └── Union
      ├── Shared Storage
      ├── Data Members
      ├── Member Functions
      └── Public by default

The most important distinction for examination purposes is:

Class and structure differ mainly in their default access control, whereas a union differs fundamentally because its non-static data members share the same storage.

September 14, 2026

Abstraction and Encapsulation, Inheritance, Polymorphism and Abstract Classes

 

Abstraction and Encapsulation, Inheritance, Polymorphism and Abstract Classes

These concepts form the core principles of Object-Oriented Programming (OOP). In C++, they allow a program to represent real-world entities, protect data, reuse existing code, and provide different implementations of the same interface.


1. Abstraction

Abstraction is the process of representing only the essential features of an object while hiding unnecessary implementation details.

In simple words, abstraction answers:

What does an object do?

rather than:

How does the object do it?

For example, when a user drives a car, the user operates the steering wheel, accelerator and brakes. The internal operation of the engine, fuel injection system and transmission is not required to be known by the user.

Similarly, in C++, a class can provide public functions through which users interact with an object while the internal implementation remains hidden.

Definition

Abstraction is an OOP mechanism that exposes the essential characteristics and operations of an object while hiding unnecessary implementation details.


1.1 Example of Abstraction

Consider a bank account:

class BankAccount
{
public:
    void withdraw(double amount)
    {
        // Internal banking logic
    }
};

The user only needs to call:

account.withdraw(5000);

The user does not need to know how the bank internally verifies the balance, records the transaction, or updates its database.

Thus, the interface exposes what operation is available, while implementation details remain hidden.


2. Abstraction in C++

Abstraction can be achieved in C++ using several mechanisms, particularly:

  • Classes

  • Access specifiers

  • Member functions

  • Abstract classes

  • Pure virtual functions

For example:

class ATM
{
private:
    int balance;

public:
    void withdraw(int amount)
    {
        if (amount <= balance)
            balance -= amount;
    }
};

Here, the user interacts with the withdraw() function without directly accessing the internal balance.


3. Encapsulation

Encapsulation is the process of bundling data and the functions that operate on that data into a single unit, usually a class.

It also provides controlled access to the internal data of an object.

Definition

Encapsulation is the mechanism of wrapping data members and member functions together within a class and controlling access to the internal data.

For example:

class Student
{
private:
    int marks;

public:
    void setMarks(int m)
    {
        if (m >= 0 && m <= 100)
            marks = m;
    }

    int getMarks()
    {
        return marks;
    }
};

Here:

  • marks is private.

  • setMarks() controls how marks are assigned.

  • getMarks() provides controlled access to marks.

The data and functions are encapsulated within the Student class.


4. Encapsulation and Data Hiding

Data hiding is an important consequence of encapsulation.

If a data member is declared as private, it cannot normally be accessed directly from outside the class.

For example:

class Account
{
private:
    double balance;

public:
    void deposit(double amount)
    {
        if (amount > 0)
            balance += amount;
    }
};

The following is not permitted from outside the class:

account.balance = -5000;   // Error

Instead, access is controlled through:

account.deposit(5000);

Therefore, encapsulation helps prevent inappropriate or uncontrolled modification of an object's state.


5. Abstraction vs Encapsulation

These two concepts are closely related but are not identical.

AbstractionEncapsulation
Focuses on what an object doesFocuses on how data and operations are packaged and protected
Hides unnecessary implementation detailsControls access to internal members
Helps reduce complexityHelps protect object state
Achieved using classes, interfaces, abstract classes, etc.Mainly implemented using classes and access specifiers
Concerned with essential featuresConcerned with bundling and access control

Easy way to remember

Abstraction → What to show

Encapsulation → What to hide/protect


6. Inheritance

Inheritance is an OOP mechanism through which a new class acquires properties and behaviour from an existing class.

The existing class is called the:

  • Base class

  • Parent class

  • Super class

The new class is called the:

  • Derived class

  • Child class

  • Sub class

Inheritance promotes code reuse and establishes a relationship between classes.

Definition

Inheritance is the mechanism by which a derived class acquires accessible data members and member functions of an existing base class.


7. Basic Syntax of Inheritance

class DerivedClass : access_specifier BaseClass
{
    // Members of derived class
};

For example:

class Animal
{
public:
    void eat()
    {
        cout << "Animal eats";
    }
};

class Dog : public Animal
{
public:
    void bark()
    {
        cout << "Dog barks";
    }
};

Here:

  • Animal → Base class

  • Dog → Derived class

  • eat() → Inherited member function

  • bark() → Derived class member function


8. Example of Inheritance

#include <iostream>
using namespace std;

class Person
{
public:
    string name;

    void displayName()
    {
        cout << "Name: " << name << endl;
    }
};

class Student : public Person
{
public:
    int rollNo;

    void displayRollNo()
    {
        cout << "Roll Number: " << rollNo << endl;
    }
};

int main()
{
    Student s;

    s.name = "Rahul";
    s.rollNo = 101;

    s.displayName();
    s.displayRollNo();

    return 0;
}

Output

Name: Rahul
Roll Number: 101

The Student class inherits the accessible member name and the function displayName() from Person.


9. Types of Inheritance

C++ supports several forms of inheritance.

9.1 Single Inheritance

One derived class inherits from one base class.

A
↓
B

Example:

class B : public A
{
};

9.2 Multilevel Inheritance

A class is derived from another derived class.

A
↓
B
↓
C

Example:

class B : public A
{
};

class C : public B
{
};

9.3 Multiple Inheritance

One derived class inherits from more than one base class.

A       B
 \     /
   \ /
    C

Example:

class C : public A, public B
{
};

9.4 Hierarchical Inheritance

Multiple derived classes inherit from the same base class.

       A
     /   \
    B     C

Example:

class B : public A
{
};

class C : public A
{
};

9.5 Hybrid Inheritance

Hybrid inheritance is a combination of two or more forms of inheritance.

For example, a combination of hierarchical and multiple inheritance can create a hybrid structure.

Image

Image

Image

Image

Image


10. Advantages of Inheritance

Inheritance provides several benefits:

  1. Code reusability – Existing functionality can be reused.

  2. Reduced code duplication – Common functionality can be placed in a base class.

  3. Easy maintenance – Common modifications can be made at the appropriate level.

  4. Extensibility – Derived classes can add new functionality.

  5. Supports polymorphism – Inheritance is an important foundation for runtime polymorphism.

  6. Logical classification – It can represent relationships such as:

Animal → Dog
Vehicle → Car
Employee → Manager
Shape → Circle

11. Polymorphism

The word polymorphism is derived from two Greek words:

  • Poly → Many

  • Morphism → Forms

Therefore, polymorphism means one interface or operation having multiple forms.

In C++, the same function name or interface can produce different behaviour depending on the context.

Definition

Polymorphism is the ability of an interface, function, or operation to exhibit different behaviours in different situations.

For example:

cout << 10 + 20;

and

cout << 10.5 + 20.5;

The + operator operates with different data types.

Similarly, a base-class interface can be used to invoke different derived-class implementations.


12. Types of Polymorphism in C++

Polymorphism in C++ is broadly classified into:

                    Polymorphism
                         |
              -----------------------
              |                     |
       Compile-time             Run-time
       Polymorphism             Polymorphism
              |                     |
       ----------------        Virtual Functions
       |              |
 Function          Operator
 Overloading       Overloading

13. Compile-Time Polymorphism

Compile-time polymorphism is resolved by the compiler during compilation.

Common examples include:

  • Function overloading

  • Operator overloading


13.1 Function Overloading

Function overloading means defining multiple functions with the same name but different parameter lists.

Example:

#include <iostream>
using namespace std;

class Calculator
{
public:
    int add(int a, int b)
    {
        return a + b;
    }

    int add(int a, int b, int c)
    {
        return a + b + c;
    }
};

int main()
{
    Calculator c;

    cout << c.add(10, 20) << endl;
    cout << c.add(10, 20, 30);

    return 0;
}

Output

30
60

The compiler determines which add() function should be called based on the arguments.


14. Operator Overloading

C++ allows many operators to be given special meaning for user-defined types.

For example, the + operator can be overloaded for adding two objects.

class Complex
{
public:
    int real, imag;

    Complex operator+(Complex c)
    {
        Complex temp;

        temp.real = real + c.real;
        temp.imag = imag + c.imag;

        return temp;
    }
};

Here, the + operator has been defined for objects of the Complex class.

This is another example of compile-time polymorphism.


15. Run-Time Polymorphism

Run-time polymorphism is achieved primarily through virtual functions and overriding in an inheritance hierarchy.

The appropriate function implementation is selected during program execution.

Consider:

class Animal
{
public:
    virtual void sound()
    {
        cout << "Animal makes a sound";
    }
};

class Dog : public Animal
{
public:
    void sound() override
    {
        cout << "Dog barks";
    }
};

Now:

Animal *ptr;
Dog d;

ptr = &d;
ptr->sound();

Output

Dog barks

Although ptr is an Animal*, it points to a Dog object. Because sound() is virtual, the overridden Dog::sound() is selected at runtime.


16. Method Overriding

When a derived class provides its own implementation of a member function already provided by the base class, it is called function overriding.

Example:

class Animal
{
public:
    virtual void sound()
    {
        cout << "Animal sound";
    }
};

class Cat : public Animal
{
public:
    void sound() override
    {
        cout << "Cat meows";
    }
};

The derived class Cat overrides the sound() function.


17. Abstraction, Encapsulation, Inheritance and Polymorphism Together

These concepts work together to provide the major advantages of OOP.

Consider a simple vehicle management system.

                    Vehicle
                       |
              -------------------
              |                 |
             Car              Bike
              |                 |
           start()           start()

The Vehicle class can define a common interface.

Car and Bike can provide their own implementations.

  • Abstraction → Only necessary vehicle operations are exposed.

  • Encapsulation → Internal vehicle data is protected.

  • InheritanceCar and Bike inherit from Vehicle.

  • Polymorphismstart() can behave differently for Car and Bike.

These four concepts therefore complement one another.


18. Abstract Class

An abstract class is a class that is designed to act as a base class and cannot be instantiated directly.

In C++, a class becomes abstract when it contains at least one pure virtual function.

Definition

An abstract class is a class containing at least one pure virtual function and cannot be used to create objects directly.


19. Pure Virtual Function

A pure virtual function is a virtual function declared using = 0.

Syntax

virtual return_type functionName() = 0;

Example:

class Shape
{
public:
    virtual void draw() = 0;
};

Here:

virtual void draw() = 0;

is a pure virtual function.

Therefore, Shape becomes an abstract class.


20. Example of Abstract Class

#include <iostream>
using namespace std;

class Shape
{
public:
    virtual void area() = 0;
};

class Circle : public Shape
{
private:
    float radius;

public:
    Circle(float r)
    {
        radius = r;
    }

    void area() override
    {
        cout << "Area of Circle = "
             << 3.14 * radius * radius;
    }
};

int main()
{
    Circle c(5);

    c.area();

    return 0;
}

Output

Area of Circle = 78.5

Here:

  • Shape → Abstract class

  • area() → Pure virtual function

  • Circle → Derived class

  • Circle::area() → Overridden function

  • c → Object of Circle

The following is not allowed:

Shape s;       // Error

because Shape is an abstract class.


21. Why Are Abstract Classes Used?

Abstract classes are useful when we want to define a common interface for a group of related classes without providing a complete implementation at the base-class level.

For example:

                 Shape
                   |
          ------------------
          |        |       |
        Circle  Rectangle  Triangle

All shapes have an area(), but the calculation is different for each shape.

Therefore, the base class can specify:

virtual void area() = 0;

and each derived class can provide its own implementation.

This is an important application of abstraction and runtime polymorphism.


22. Abstract Class with Multiple Derived Classes

#include <iostream>
using namespace std;

class Shape
{
public:
    virtual void area() = 0;
};

class Circle : public Shape
{
public:
    void area() override
    {
        cout << "Area of Circle" << endl;
    }
};

class Rectangle : public Shape
{
public:
    void area() override
    {
        cout << "Area of Rectangle" << endl;
    }
};

int main()
{
    Circle c;
    Rectangle r;

    c.area();
    r.area();

    return 0;
}

Output

Area of Circle
Area of Rectangle

Both derived classes follow the common interface provided by Shape, but each implements the operation differently.


23. Abstract Class and Polymorphism

Abstract classes are particularly useful when combined with base-class pointers or references.

Shape *ptr;

Circle c;
Rectangle r;

ptr = &c;
ptr->area();

ptr = &r;
ptr->area();

The same pointer:

Shape *ptr

can refer to different derived-class objects.

The call:

ptr->area();

can therefore execute different implementations depending on the actual object.

This demonstrates runtime polymorphism.


24. Difference Between Concrete and Abstract Classes

Concrete ClassAbstract Class
Can be instantiatedCannot be instantiated
Objects can be created directlyObjects cannot be created directly
Does not necessarily contain pure virtual functionsContains at least one pure virtual function
Can be used as a normal classPrimarily used as a base class
Provides complete implementation where requiredMay define an interface requiring derived classes to implement operations

25. Difference Between Abstraction and Abstract Class

These terms should not be treated as synonyms.

Abstraction is an OOP principle.

An abstract class is a C++ language mechanism that can be used to implement abstraction.

For example:

class Shape
{
public:
    virtual void area() = 0;
};

The concept of hiding unnecessary implementation details is abstraction, while Shape being non-instantiable because of its pure virtual function makes it an abstract class.


26. Overall Comparison of Four Major OOP Concepts

ConceptMain PurposeC++ Mechanism
AbstractionHide unnecessary implementation detailsClasses, interfaces through classes, abstract classes
EncapsulationBundle and protect data and operationsClasses, access specifiers
InheritanceReuse and extend existing classes: inheritance syntax
PolymorphismAllow one interface to have multiple behavioursOverloading, overriding, virtual functions

27. Important Points for Students

  • Abstraction hides unnecessary implementation details.

  • Encapsulation combines data and functions and controls access to data.

  • private members are useful for implementing data hiding.

  • Inheritance allows a derived class to reuse and extend a base class.

  • C++ supports single, multiple, multilevel, hierarchical and hybrid inheritance.

  • Polymorphism means one interface having multiple forms.

  • Function overloading is an example of compile-time polymorphism.

  • Operator overloading is also a form of compile-time polymorphism.

  • Virtual functions support runtime polymorphism.

  • Function overriding occurs when a derived class provides a new implementation of an inherited virtual function.

  • A pure virtual function is declared using = 0.

  • A class containing at least one pure virtual function is an abstract class.

  • An abstract class cannot be instantiated directly.

  • Abstract classes are useful for defining a common interface for derived classes.

  • Abstraction and encapsulation are related, but they represent different OOP concepts.

Quick Memory Rule

Abstraction → Hide complexity
Encapsulation → Protect data
Inheritance → Reuse code
Polymorphism → One interface, many behaviours
Abstract Class → Common interface without direct object creation

September 14, 2026

Classes and Objects, Methods and Messages

 

Classes and Objects, Methods and Messages

1. Introduction

Object-Oriented Programming (OOP) is a programming approach in which a program is designed around objects rather than only around functions and procedures. An object represents a real-world entity such as a student, employee, bank account, car, or sensor. Each object contains data representing its state and functions representing its behaviour.

In C++, the fundamental building blocks of object-oriented programming are classes and objects. A class defines the structure and behaviour of objects, while an object is an actual instance of a class. Objects communicate with each other through method calls, commonly described in OOP terminology as message passing.

The relationship can be represented as:

Class → Blueprint/Definition → Objects → Actual entities

For example, Student can be defined as a class. Individual students such as student1 and student2 are objects of the Student class.


2. Class

A class is a user-defined data type that groups related data members and member functions into a single unit.

The data members represent the state of an object, whereas member functions represent its behaviour.

For example, a Student class may contain:

  • Roll number

  • Name

  • Marks

and functions such as:

  • readData()

  • displayData()

  • calculateGrade()

Thus, a class provides a logical representation of an entity and specifies what data an object will contain and what operations can be performed on that data.

Definition

A class is a user-defined data type that encapsulates data members and member functions into a single unit and serves as a blueprint for creating objects.


3. General Syntax of a Class

class ClassName
{
    access_specifier:

        data_members;

        member_functions;
};

For example:

class Student
{
private:
    int rollNo;
    float marks;

public:
    void input();
    void display();
};

Here:

  • class is the C++ keyword used to declare a class.

  • Student is the class name.

  • rollNo and marks are data members.

  • input() and display() are member functions.

  • private and public are access specifiers.

  • The semicolon after the closing brace is mandatory.


4. Components of a Class

A class generally consists of two major components:

4.1 Data Members

Data members are variables declared inside a class. They represent the properties or state of an object.

Example:

class Student
{
    int rollNo;
    float marks;
};

Here, rollNo and marks are data members.

4.2 Member Functions

Member functions are functions declared inside a class that define the behaviour or operations of its objects.

Example:

class Student
{
    int rollNo;
    float marks;

public:
    void display()
    {
        cout << rollNo << endl;
        cout << marks << endl;
    }
};

Here, display() is a member function.


5. Access Specifiers

C++ provides three main access specifiers:

Access SpecifierAccessibility
privateAccessible only within the class
publicAccessible from outside the class
protectedAccessible within the class and derived classes

The default access specifier of a class in C++ is private.

For example:

class Student
{
    int rollNo;       // private by default

public:
    void display()
    {
        cout << rollNo;
    }
};

The variable rollNo cannot normally be accessed directly through an object from outside the class.


6. Object

An object is an instance of a class.

When a class is defined, memory is generally not allocated for its non-static data members merely because the class definition exists. Memory for those data members is associated with objects when objects are created.

For example:

class Student
{
public:
    int rollNo;

    void display()
    {
        cout << rollNo;
    }
};

int main()
{
    Student s1;
    Student s2;

    return 0;
}

Here:

  • Student → class

  • s1 → object

  • s2 → object

Both s1 and s2 are objects of the Student class.

Each object has its own copy of the non-static data members.


7. Class and Object Relationship

A class can be considered a blueprint, whereas an object is the actual entity created using that blueprint.

For example, consider a building design.

Image

Image

Image

Image

Image

A building plan describes the structure of a building, but the plan itself is not the physical building. Similarly, a class describes the properties and behaviour of objects, while an object is the actual instance.

For example:

class Car
{
public:
    string color;
    void start()
    {
        cout << "Car started";
    }
};

Objects can then be created:

Car car1;
Car car2;
Car car3;

Here, Car defines the common structure and behaviour, while car1, car2, and car3 are individual objects.


8. Creating Objects

Objects can be created using the class name followed by the object name.

Syntax

ClassName objectName;

Example:

Student s1;

Multiple objects can also be declared:

Student s1, s2, s3;

Objects may also be created dynamically using pointers and new, but static/local object creation is sufficient for understanding the basic concept.


9. Accessing Members of an Object

The dot (.) operator is used to access accessible members of an object.

Syntax

objectName.memberName;

For example:

class Student
{
public:
    int rollNo;

    void display()
    {
        cout << rollNo;
    }
};

int main()
{
    Student s1;

    s1.rollNo = 101;
    s1.display();

    return 0;
}

Output

101

Here:

s1.rollNo = 101;

assigns a value to the data member of object s1.

Similarly:

s1.display();

invokes the display() member function for object s1.


10. Complete Example of Class and Object

Consider the following program:

#include <iostream>
using namespace std;

class Student
{
private:
    int rollNo;
    float marks;

public:
    void setData(int r, float m)
    {
        rollNo = r;
        marks = m;
    }

    void display()
    {
        cout << "Roll Number: " << rollNo << endl;
        cout << "Marks: " << marks << endl;
    }
};

int main()
{
    Student s1;

    s1.setData(101, 85.5);
    s1.display();

    return 0;
}

Output

Roll Number: 101
Marks: 85.5

Explanation

The class Student contains two private data members:

int rollNo;
float marks;

Since these members are private, they cannot be directly accessed from main().

The public member function:

setData()

is used to assign values to them.

The function:

display()

is used to display the values.

The statement:

Student s1;

creates an object named s1.

The statement:

s1.setData(101, 85.5);

calls the setData() method for object s1.


11. Methods in C++

In general OOP terminology, a method is an operation or function associated with an object or class.

In C++, methods are commonly implemented as member functions.

For example:

class Calculator
{
public:
    int add(int a, int b)
    {
        return a + b;
    }
};

Here, add() is a member function and can be considered a method of the Calculator class.

An object can invoke the method:

Calculator c;

cout << c.add(10, 20);

Output:

30

12. Types of Methods

Depending upon their purpose, member functions can perform different operations.

12.1 Accessor Method

An accessor method is used to access or retrieve the value of a data member.

Example:

int getMarks()
{
    return marks;
}

Such functions are commonly called getter methods.

12.2 Mutator Method

A mutator method modifies or assigns the value of a data member.

Example:

void setMarks(int m)
{
    marks = m;
}

Such functions are commonly called setter methods.

12.3 Other Behavioural Methods

A class may also contain methods that perform calculations or other operations.

Example:

float calculatePercentage()
{
    return totalMarks / 5.0;
}

Thus, methods define what an object can do.


13. Defining a Member Function Outside the Class

A member function can be defined outside the class using the scope resolution operator (::).

Example:

#include <iostream>
using namespace std;

class Student
{
private:
    int marks;

public:
    void setMarks(int m);
    void display();
};

void Student::setMarks(int m)
{
    marks = m;
}

void Student::display()
{
    cout << "Marks: " << marks;
}

int main()
{
    Student s1;

    s1.setMarks(85);
    s1.display();

    return 0;
}

Here:

Student::setMarks()

means that setMarks() belongs to the Student class.

Similarly:

Student::display()

defines the display() member function outside the class.


14. Methods and Objects

A method operates in the context of an object.

Consider:

class BankAccount
{
private:
    double balance;

public:
    void deposit(double amount)
    {
        balance += amount;
    }

    void displayBalance()
    {
        cout << balance;
    }
};

Suppose two objects are created:

BankAccount account1;
BankAccount account2;

When we write:

account1.deposit(5000);

the method operates on account1.

When we write:

account2.deposit(3000);

the same method operates on account2.

Thus, the same member function can operate on different objects, with each object maintaining its own state.


15. Messages in Object-Oriented Programming

In OOP, objects communicate with one another by sending messages.

A message essentially represents a request to an object to perform a particular operation.

For example:

student.display();

can conceptually be viewed as:

Send a display message to the student object.

Similarly:

account.deposit(5000);

can be understood as:

Send a deposit message with the value 5000 to the account object.

In C++, message passing is primarily implemented through member-function calls.


16. Message Structure

A message generally contains:

  1. Receiver object – the object that receives the request.

  2. Method/function name – the operation to be performed.

  3. Arguments – optional information required by the method.

For example:

account.deposit(5000);

Here:

ComponentExample
Receiver objectaccount
Methoddeposit()
Argument5000

Conceptually:

Object → Message → Method Execution → Result/State Change

Image

Image

Image

Image

Image

Image


17. Example of Message Passing

Consider two classes representing a simple interaction:

#include <iostream>
using namespace std;

class Printer
{
public:
    void printMessage()
    {
        cout << "Hello from Printer";
    }
};

class Computer
{
public:
    void sendToPrinter(Printer &p)
    {
        p.printMessage();
    }
};

int main()
{
    Printer p1;
    Computer c1;

    c1.sendToPrinter(p1);

    return 0;
}

Output

Hello from Printer

The important statement is:

p.printMessage();

The Computer object invokes a method of the Printer object. From the OOP perspective, the Printer object receives a request to perform the printMessage() operation.


18. Message Passing and Encapsulation

Message passing is closely related to encapsulation.

An object's internal data can be kept private, and other objects interact with it through publicly available methods.

For example:

class BankAccount
{
private:
    double balance;

public:
    void deposit(double amount)
    {
        if (amount > 0)
            balance += amount;
    }
};

An external object cannot directly manipulate:

balance

if it is private.

Instead, it communicates through:

account.deposit(5000);

This provides controlled access to the object's state.


19. Class, Object, Method and Message

These four concepts are closely related but should not be confused.

ConceptMeaningExample
ClassBlueprint/user-defined typeStudent
ObjectInstance of a classs1
MethodOperation/member functiondisplay()
MessageRequest sent to an object to perform an operations1.display()

Consider:

Student s1;

s1.display();

Here:

  • Student is the class.

  • s1 is the object.

  • display() is the method/member function.

  • s1.display() represents the message/request sent to s1.


20. Real-World Analogy

Consider a bank account.

The bank account can be represented as an object.

Its state may include:

  • Account number

  • Account holder

  • Balance

Its behaviour may include:

  • Deposit

  • Withdraw

  • Check balance

For example:

account.deposit(5000);
account.withdraw(1000);
account.checkBalance();

Each statement represents an operation requested from the account object.

Thus:

Object: account

Messages/requests:

deposit(5000)
withdraw(1000)
checkBalance()

The object internally manages its state while exposing appropriate operations to the outside world.


21. Important Characteristics of Classes and Objects

Class

  • Provides a blueprint for objects.

  • Combines data and functions.

  • Supports encapsulation.

  • Defines the properties and behaviour common to its objects.

  • Can contain private, protected and public members.

Object

  • Is an instance of a class.

  • Has its own state.

  • Can invoke accessible methods.

  • Can interact with other objects.

  • Occupies memory for its non-static data members.

Methods

  • Define the behaviour of objects.

  • Can access members of their class according to access rules.

  • May accept arguments and return values.

  • Can be defined inside or outside the class.

Messages

  • Represent requests between objects.

  • In C++, commonly implemented through member-function calls.

  • May contain arguments.

  • Allow objects to cooperate to perform a larger task.


22. Simple Conceptual View

The overall concept can be understood as:

Image

Image

Image

Image

Image

Class

↓ creates

Objects

↓ communicate through

Messages / Method Calls

↓ execute

Methods

↓ modify or retrieve

Object State

This forms the basic interaction model of object-oriented programming.


23. Key Points to Remember

  1. A class is a user-defined data type and acts as a blueprint for objects.

  2. An object is an instance of a class.

  3. Data members represent the state of an object.

  4. Member functions/methods represent the behaviour of an object.

  5. The dot (.) operator is generally used to access accessible members through an object.

  6. C++ uses the scope resolution operator (::) to define a member function outside its class.

  7. Objects can communicate by sending messages.

  8. In C++, message passing is primarily represented through member-function calls.

  9. Encapsulation protects an object's internal state and provides controlled interaction through methods.

  10. A single class can be used to create multiple objects, each maintaining its own non-static data.


24. Short Example for Examination

#include <iostream>
using namespace std;

class Rectangle
{
private:
    int length, breadth;

public:
    void setData(int l, int b)
    {
        length = l;
        breadth = b;
    }

    int area()
    {
        return length * breadth;
    }
};

int main()
{
    Rectangle r1;

    r1.setData(10, 5);

    cout << "Area = " << r1.area();

    return 0;
}

Output

Area = 50

Concept involved

In this example:

  • RectangleClass

  • r1Object

  • setData()Method

  • area()Method

  • r1.setData(10, 5)Message/method call

  • r1.area()Message/method call

  • length and breadthData members

  • private → Provides data protection/encapsulation

This example therefore demonstrates the relationship among classes, objects, methods and messages in C++.