Computer Science and IT‹›⌂ 0:00 studied

Module 12 · 14 min read · Free chapter

Object-oriented concepts with C++, Java and Python basics

In short

Object-oriented programming bundles data and methods into classes, whose instances are objects. Its four pillars are encapsulation, abstraction, inheritance and polymorphism. Overloading is resolved at compile time and overriding of virtual functions at run time through a vtable. Java compiles to bytecode run by the JVM, while Python is dynamically typed.

What are you preparing for? We show the practice and previous year questions of your exam.

Start from zero: forms, passbooks and objects

Walk into any bank branch and ask for a savings account. The clerk gives you a printed form with blank boxes for name, address and opening balance. Thousands of people fill the same form, but each filled form describes a different person.

The blank form is like a class: it says what information every account has and what can be done with it, such as deposit and withdraw. Each filled form, or each passbook, is like an object: it holds its own name and its own balance. Meena's deposit changes only Meena's balance, not Ravi's.

Older programs kept data in one place and functions in another, and any function could change any data. Object-oriented programming (OOP) keeps each piece of data together with the functions allowed to touch it. The result is code that is easier to understand, test and reuse, which matters when a team maintains a system for years.

Why it matters. Most software written today, from banking apps to railway booking, is built with C++, Java or Python, and all three are object-oriented. IT officer and RRB JE IT papers therefore ask about classes, inheritance and polymorphism every year.

Classes, objects, encapsulation and access

A class declares data members (attributes) and member functions (methods). An object is an instance of the class, and each object gets its own copy of the data members, while the code of the methods is shared. Creating an object is called instantiation.

OOP rests on four ideas. Encapsulation bundles data with the methods that use it and hides the data from outside code. Abstraction shows users only the essential interface, such as deposit(), and hides how it works. Inheritance lets a new class reuse and extend an old one, and polymorphism lets one interface behave in many forms.

Encapsulation is enforced by access specifiers. In C++, private members are reachable only inside the class, protected members also in derived classes, and public members everywhere. Members of a class are private by default, while members of a struct are public by default, which is the only real difference between the two.

Java has four levels: private, default (visible within the same package, with no keyword), protected and public. Python has no enforced privacy. A name that starts with two underscores is quietly renamed inside the class, which is called name mangling, so outside code cannot reach it by its plain name.

class Account:
    def __init__(self, owner, balance):
        self.owner = owner
        self.__balance = balance

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount

    def balance(self):
        return self.__balance

a = Account("Meena", 1000)
a.deposit(500)
print(a.balance())
try:
    print(a.__balance)
except AttributeError:
    print("no direct access")

Output:

1500
no direct access

The deposit goes through the method, which checks that the amount is positive. The direct read of a.__balance fails, because inside the class the name was mangled. So the only way to change the balance is through methods that enforce the bank's rules.

Why it matters. Encapsulation means a bug in the balance can come only from a few methods, not from anywhere in a large program. That is why exams ask which specifier to use and what a class's default access is.

Constructors, destructors and inheritance

When an object is created, its data must start in a valid state. A constructor does this. In C++ it has the same name as the class and no return type, not even void, and it runs automatically when the object is created.

A constructor can be default (no arguments), parameterised, or a copy constructor that builds a new object from an existing one. Constructors can be overloaded, so a class may have several. In Python the method __init__ plays the same role.

A destructor, written as ~ClassName(), runs when the object's life ends and releases what it holds, such as memory or an open file. It takes no arguments and cannot be overloaded, so a class has only one. When objects are built in a chain, the destructors run in the reverse order of the constructors.

Inheritance lets a derived class take the members of a base class and add its own. A SavingsAccount can inherit deposit() from Account and add addInterest(). There are five common shapes, listed in the table below.

Type Shape Example
Single One base, one derived class. Account to SavingsAccount.
Multiple One class has two or more bases. SmartPhone from Phone and Camera.
Multilevel A chain of bases. Vehicle to Car to ElectricCar.
Hierarchical One base, many derived classes. Employee to Clerk and Manager.
Hybrid A mix of two or more of the above. A diamond of four classes.

Multiple inheritance can cause the diamond problem. If B and C both inherit from A, and D inherits from both B and C, then D gets two copies of A's members, and a call becomes ambiguous. C++ solves this with virtual base classes, so that only one copy of A is kept.

Java avoids the problem by allowing a class to extend only one class, while it may implement many interfaces. Python allows multiple inheritance and searches the bases in a fixed order called the method resolution order.

Why it matters. Inheritance is the main tool for reuse in OOP, and questions on constructor order, destructor order and which languages allow multiple inheritance are common one-mark items.

Polymorphism: overloading, overriding and virtual functions

Polymorphism means "many forms": one name, different behaviour. Compile-time (static) polymorphism is decided by the compiler before the program runs, through function overloading and operator overloading. Run-time (dynamic) polymorphism is decided while the program runs, through overriding.

Point Overloading Overriding
Where Same class or scope. Base and derived class.
Signature Same name, different parameter lists. Same name and same parameters.
Decided at Compile time. Run time, for virtual functions.

A different return type alone cannot overload a function, because the compiler picks the version from the arguments of the call. Now look at what C++ does when a base-class pointer points to a derived object.

#include <iostream>
using namespace std;

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

class Base {
public:
    void hello() { cout << "Base hello" << endl; }
    virtual void greet() { cout << "Base greet" << endl; }
};
class Derived : public Base {
public:
    void hello() { cout << "Derived hello" << endl; }
    void greet() override { cout << "Derived greet" << endl; }
};

int main() {
    cout << add(2, 3) << " " << add(2.5, 1.0) << endl;
    Derived d;
    Base* p = &d;
    p->hello();
    p->greet();
    return 0;
}

Output:

5 3.5
Base hello
Derived greet

The two calls to add pick different versions from the argument types, which is overloading. hello() is not virtual, so the compiler binds the call by the pointer's type and prints "Base hello". greet() is virtual, so the call is bound at run time by the object's type and prints "Derived greet".

How does the program find the right greet at run time? Compilers usually give each class that has virtual functions a virtual table (vtable), which is an array of pointers to that class's versions. Each object of such a class carries a hidden pointer, the vptr, to its class's vtable, so a virtual call costs one extra lookup.

This also explains the virtual destructor rule. If a derived object is deleted through a base pointer and the base destructor is not virtual, only the base destructor runs and the derived part is never cleaned up.

#include <iostream>
using namespace std;

class Shape {
public:
    virtual double area() const { return 0; }
    virtual ~Shape() { cout << "~Shape" << endl; }
};

class Rect : public Shape {
    double w, h;
public:
    Rect(double w, double h) : w(w), h(h) { cout << "Rect built" << endl; }
    double area() const override { return w * h; }
    ~Rect() { cout << "~Rect" << endl; }
};

int main() {
    Shape* s = new Rect(3, 4);
    cout << s->area() << endl;
    delete s;
    return 0;
}

Output:

Rect built
12
~Rect
~Shape

The virtual area() gives 3×4=123 \times 4 = 12, and because ~Shape is virtual, ~Rect runs first and ~Shape after it. Constructors, by contrast, can never be virtual, because the vptr is set up only while the object is being constructed.

Why it matters. Run-time polymorphism lets a booking system call fare() on any ticket type without knowing which one it is, so a new type can be added without touching old code. "What does this code print?" questions on virtual and non-virtual calls are a favourite in IT officer papers.

Abstract classes and interfaces

Some classes describe an idea that is too general to exist on its own, such as "Shape" or "Employee". An abstract class captures such an idea, and no object of it can be created. It exists to be inherited.

In C++ a class becomes abstract when it has at least one pure virtual function, written as virtual double area() const = 0;. Every concrete derived class must define that function, or it stays abstract too. In Java the keyword abstract marks both the class and the bodiless methods.

An interface in Java is a pure contract: it lists methods that every implementing class must provide. Interface methods without a body are implicitly public and abstract. A class can implement many interfaces, which is how Java gets the benefit of multiple inheritance without the diamond problem.

interface Payable {
    double pay();
}

abstract class Employee implements Payable {
    protected String name;
    Employee(String name) { this.name = name; }
    public abstract double pay();
}

class Clerk extends Employee {
    Clerk(String name) { super(name); }
    public double pay() { return 25000; }
}

class Manager extends Employee {
    Manager(String name) { super(name); }
    public double pay() { return 60000; }
}

public class Main {
    public static void main(String[] args) {
        Payable[] staff = { new Clerk("Asha"), new Manager("Ravi") };
        for (Payable p : staff) {
            System.out.println(p.pay());
        }
    }
}

Output:

25000.0
60000.0

The loop holds only Payable references, yet each call runs the right pay(), which is run-time polymorphism through an interface. The values print as 25000.0 and 60000.0 because pay() returns a double. The call super(name) runs the base constructor first, as in C++.

Why it matters. Abstract classes and interfaces let a team agree on what every part must do before anyone writes how. A payroll module can be written against Payable today and still work for a new Contractor class added next year.

Java's JVM and garbage collection, and Python's dynamic typing

C++ is compiled straight into machine code for one kind of processor. Java takes a different route. The compiler javac turns Main.java into bytecode stored in .class files, and the Java Virtual Machine (JVM) runs that bytecode.

The JVM interprets bytecode and compiles the frequently run parts into machine code just in time (JIT). Since every platform has its own JVM, the same .class file runs on Windows, Linux or a phone, which is the idea behind "write once, run anywhere". Bytecode is not machine code, so it always needs a JVM to run.

Java also manages memory for you. Objects are created with new on the heap, and when no reference can reach an object any more, the garbage collector frees it automatically. So Java has no delete operator and no destructor, which removes whole classes of bugs such as freeing memory twice.

Python goes further in flexibility. It is dynamically typed: the type belongs to the value, not to the variable, so a name can hold an integer now and a string later. It also uses duck typing: if an object has the method you call, the call works, whatever the object's class ("if it walks like a duck and quacks like a duck, it is a duck").

class Dog:
    def speak(self):
        return "Bhow"

class Robot:
    def speak(self):
        return "Beep"

x = 10
print(type(x).__name__)
x = "ten"
print(type(x).__name__)
for thing in [Dog(), Robot()]:
    print(thing.speak())

Output:

int
str
Bhow
Beep

Dog and Robot share no base class, yet the loop calls speak() on both. The cost of this freedom is that a wrong type is caught only when that line runs, not before. In Python every value, even an integer, is an object, and memory is also freed automatically.

Why it matters. Exams often ask why Java is platform independent and what bytecode is, and they contrast static typing in C++ and Java with dynamic typing in Python. Knowing who frees memory in each language is also a common one-mark question.

Descriptive lens: how written papers ask this

GATE does not test this chapter, but written papers for IT officer posts, state Assistant Programmer exams and university tests ask about OOP in four ways:

  1. Explain the four pillars of OOP with a small example of each.
  2. Compare pairs such as overloading and overriding, abstract class and interface, or C++ and Java memory management.
  3. Trace a short program with constructors, destructors and virtual calls and write its output.
  4. Design a small class hierarchy for a given situation, such as a library, a bank or a ticketing system.

Practice questions (our own, not previous-year questions).

  1. Distinguish compile-time and run-time polymorphism. Explain, with a C++ example, why a base-class destructor should be virtual. (15 marks)
  2. What is the diamond problem in multiple inheritance? How do C++ and Java each deal with it? (10 marks)
  3. Design classes for a railway ticketing system with general, sleeper and AC tickets, showing where you would use an abstract class and an overridden method. (10 marks)

Answer plan for question 1.

  • Define polymorphism as one interface with many forms, and state that it is resolved either at compile time or at run time.
  • Explain that compile-time polymorphism uses function and operator overloading, where the compiler picks the version from the argument types.
  • Explain that run-time polymorphism uses overriding of virtual functions, where the call is bound by the actual object's type through the vtable.
  • Give the Shape and Rect example, and show that deleting a Rect through a Shape pointer runs both destructors only when the Shape destructor is virtual.
  • Conclude that any class meant to be used as a base through pointers should have a virtual destructor, or memory and resources may leak.

Quick revision

  • A class is a blueprint, and an object is an instance with its own copy of the data.
  • The four pillars are encapsulation, abstraction, inheritance and polymorphism.
  • C++ class members are private by default, struct members are public by default, and Java's default is package access.
  • A constructor has the class's name and no return type, and destructors run in the reverse order of construction.
  • C++ and Python allow multiple inheritance of classes, while a Java class extends one class and implements many interfaces.
  • Overloading is decided at compile time, and overriding of virtual functions is decided at run time.
  • A virtual call uses the object's vtable through its hidden vptr, and a base destructor should be virtual.
  • A class with a pure virtual function is abstract in C++, and no object of an abstract class can be created.
  • Java compiles to bytecode that the JVM runs, and the garbage collector frees unreachable objects.
  • Python is dynamically and strongly typed, and it uses duck typing.

Check yourself

Exam-style questions on this chapter. Pick an answer to see the explanation. 0 of 15 answered

  1. Which statement about classes and objects is correct?

  2. Bundling data with the methods that use it and hiding the data from outside code is called:

  3. In C++, the default access of members declared in a class (not a struct) is:

  4. Which statement about C++ constructors and destructors is FALSE?

  5. How does a Java class get the benefit of multiple inheritance?

  6. In C++, the diamond problem of multiple inheritance is solved by:

  7. Which is an example of run-time polymorphism?

  8. Two C++ functions have the same name and the same parameters but different return types. The result is:

  9. Base has a non-virtual hello() and a virtual greet(); Derived overrides both. With Base* p pointing to a Derived object, p->hello(); p->greet(); prints:

  10. Why should a base class destructor be virtual?

  11. A C++ class becomes abstract when it:

  12. In the Java sample, an array of Payable references holds a Clerk (pay 25000) and a Manager (pay 60000), and pay() returns double. The loop prints:

  13. Java programs are platform independent mainly because:

  14. x = 10 and then x = "ten" in Python. This works because Python is:

  15. Which statement about the GATE 2026 CS syllabus is correct?

Previous year questions

Previous year questions for UPSC CSE will appear here once each one is checked word for word against the official question paper.

Learn with AI

A tutor that asks instead of telling, a partner that argues the other side, and this chapter told through your own district.

Tell the tutor what you are stuck on. It will guide you with questions and give the answer after a few tries.

🙋 Raise a doubt or feedback

Stuck somewhere, or spotted a mistake? Write to the ExamHike team. We usually reply within a day, and you will see the reply on My progress.

Log in to ask a doubt or send feedback →

Frequently asked questions

What is the difference between overloading and overriding?

Overloading uses one name with different parameter lists in the same scope; overriding redefines a base method with the same signature in a derived class.

Why should a base class destructor be virtual?

So that deleting a derived object through a base pointer runs the derived destructor as well as the base one.

Does Java support multiple inheritance?

A Java class can extend only one class, but it can implement many interfaces.

Why is Java platform independent?

javac produces bytecode, and the same bytecode runs on any machine that has a JVM.

More in this module: Software engineering, OOP and web

Official sources

Facts in this chapter were checked against these official sources.

  1. GATE 2026 Computer Science and Information Technology (CS) syllabus, IIT Guwahati
  2. NPTEL Software Engineering (IIT Kharagpur, 106105182): object-oriented concepts and design