2 Classes Objects And Data Members

Object Oriented Programming · Unit 2

Classes, Objects, and Data Members

Exam-focused notes for Classes, Objects, and Data Members (Object Oriented Programming, BIT153): what the TU syllabus asks and how it has actually been tested, with 4 solved past questions from this unit.

Classes, Objects, and Data Members in short

A class is the base of all C++ object-oriented code. This chapter shows how to declare a class, control access to its members, create objects and pass them to and from functions.

Classes, Objects, and Data Members: notes

Class definition and declaration

A class is declared with the keyword class, followed by its name and a body in braces. The body ends with a semicolon. The body holds data members and member functions.

class Rectangle {
private:
    float length, width;       // data members
public:
    void setData(float l, float w);   // declaration
    float area();
};

The declaration only describes the class. No memory is used until we create an object. Member functions can be defined inside the class (they become inline) or outside using the scope resolution operator ::.

Data members and member functions

Data members are the variables of a class. They store the state of the object. Member functions are the functions of a class. They work on the data members.

class Rectangle {
    float length, width;
public:
    void setData(float l, float w) { length = l; width = w; }
    float area() { return length * width; }
};

int main() {
    Rectangle r;
    r.setData(5, 3);
    cout << r.area();      // 15
}

We call a member function with the dot operator: object.function(). With a pointer to an object we use the arrow operator: ptr->function().

Member functions can be called by other member functions of the same class directly, without the dot operator.

What this unit covers

  • Class definition and declaration
  • Data members and member functions
  • Access specifiers: public, private, protected
  • Objects as instances of classes
  • Objects as function arguments
  • Returning objects from functions

Returning objects from functions

2081 · 5 marks

How do you return object in function? Describe with an example. [5]

In C++, a function can return an object of a class just like it returns any other data type. The return type of the function is specified as the class name, and the return statement returns an object of that class. Syntax: --- - The return type of the function must be the class name. - A temporar...

Open this answer on its own page →

2080 · 5 marks

Write a program to demonstrate returning object from functions in C++. [5]

In C++, a function can return an object of a class just like it returns any other data type. The returned object is a copy of the local object created inside the function. Point Explanation -------------------- Return type The return type of add() is Rectangle (a class type) Local object temp is ...

Open this answer on its own page →

More from this unit

2079 · 10 marks

Explain the chain of constructor and destructor between sub classes and super classes during inheritance with example.Create a class named 'Point' with data members x and y. Overload the + operator to add the value of two objects of this class.[5+5]

Show solved answer

Chain of Constructor and Destructor in Inheritance + Operator Overloading


(a) Chain of Constructor and Destructor in Inheritance

Concept

In C++ inheritance, when an object of a derived (sub) class is created or destroyed, constructors and destructors are called in a specific order involving both the base (super) class and the derived class.

Constructor Chaining (Order of Execution)

When a derived class object is created:

  1. Base class constructor is called FIRST
  2. Derived class constructor is called SECOND

This ensures that the base part of the object is fully initialized before the derived part uses it.

Destructor Chaining (Order of Execution)

When a derived class object is destroyed:

  1. Derived class destructor is called FIRST
  2. Base class destructor is called SECOND

The destructor order is the exact reverse of constructor order.

Constructor Order:    Base --> Derived
Destructor Order:     Derived --> Base

Example

#include <iostream>
using namespace std;

// Super class (Base class)
class Animal {
public:
    Animal() {
        cout << "Animal Constructor called" << endl;
    }
    ~Animal() {
        cout << "Animal Destructor called" << endl;
    }
};

// Sub class (Derived class)
class Dog : public Animal {
public:
    Dog() {
        cout << "Dog Constructor called" << endl;
    }
    ~Dog() {
        cout << "Dog Destructor called" << endl;
    }
};

// Further derived class
class Puppy : public Dog {
public:
    Puppy() {
        cout << "Puppy Constructor called" << endl;
    }
    ~Puppy() {
        cout << "Puppy Destructor called" << endl;
    }
};

int main() {
    cout << "Creating Puppy object:" << endl;
    Puppy p;
    cout << "\nObject going out of scope:" << endl;
    return 0;
}

Output

Creating Puppy object:
Animal Constructor called
Dog Constructor called
Puppy Constructor called

Object going out of scope:
Puppy Destructor called
Dog Destructor called
Animal Constructor called

Summary Table

EventOrder
Object CreationBase --> Intermediate --> Derived
Object DestructionDerived --> Intermediate --> Base

Key Rule: Constructors run from top (most base) to bottom (most derived). Destructors run from bottom (most derived) to top (most base).


(b) Class Point with Overloaded + Operator

Concept of Operator Overloading

Operator overloading allows C++ operators (like +, -, *) to work with user-defined objects. The keyword operator is used to define the overloaded function.

Program

#include <iostream>
using namespace std;

class Point {
private:
    int x;
    int y;

public:
    // Constructor
    Point(int x = 0, int y = 0) {
        this->x = x;
        this->y = y;
    }

    // Overload + operator
    Point operator+(Point p) {
        Point temp;
        temp.x = this->x + p.x;
        temp.y = this->y + p.y;
        return temp;
    }

    // Display function
    void display() {
        cout << "Point(" << x << ", " << y << ")" << endl;
    }
};

int main() {
    Point p1(3, 4);
    Point p2(5, 6);
    Point p3;

    cout << "Point 1: ";
    p1.display();

    cout << "Point 2: ";
    p2.display();

    // Using overloaded + operator
    p3 = p1 + p2;

    cout << "Sum of Points: ";
    p3.display();

    return 0;
}

Output

Point 1: Point(3, 4)
Point 2: Point(5, 6)
Sum of Points: Point(8, 10)

Explanation

StepDescription
Point p1(3, 4)Creates object p1 with x=3, y=4
Point p2(5, 6)Creates object p2 with x=5, y=6
p1 + p2Calls p1.operator+(p2)
Inside operator+temp.x = 3+5 = 8, temp.y = 4+6 = 10
Returns tempResult stored in p3

Note: The operator+ function takes one argument (the right-hand operand) because the left-hand operand is the calling object (this). The function returns a new Point object containing the sum.

Open this answer on its own page →

Objects as function arguments

2078 · 5 marks

Explain use of objects as function arguments with example [5]

In C++, objects of a class can be passed as arguments to functions, just like variables of built-in data types. This allows functions to work with the data and behavior encapsulated within objects. When an object is passed to a function, the function receives a copy of the object (pass by value) ...

Open this answer on its own page →