Classes, Objects, and Constructors in C++ and Python

EASY7 min readby AdminJune 19, 2026History
5.0|1 ratingLog in to rate

Learn class declarations, object instantiation, and constructor behaviors in C++ and Python side-by-side.

#oop#cpp#python#classes#constructors

Understanding Classes and Instantiation

A class is a blueprint or template for creating objects. An object is an instance of a class, possessing attributes (data/state) and methods (behavior).

In C++, memory allocation can happen on either the stack (automatic, e.g. Student s1;) or the heap (manual, using the new keyword, e.g. Student* s1 = new Student();). In Python, all objects are references and memory management is handled dynamically via garbage collection.

C++ Class Declaration and Instantiation

cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>

class Student {
private:
    std::string name;
    int age;

public:
    // Parameterized Constructor
    Student(std::string n, int a) : name(n), age(a) {
        std::cout << "Constructor called for " << name << std::endl;
    }

    // Destructor
    ~Student() {
        std::cout << "Destructor called for " << name << std::endl;
    }

    void display() {
        std::cout << "Name: " << name << ", Age: " << age << std::endl;
    }
};

int main() {
    // Stack instantiation (destructor runs automatically when out of scope)
    Student s1("Alice", 20);
    s1.display();
    return 0;
}

Python Class Declaration and Instantiation

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Student:
    # Constructor (Initializer)
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age
        print(f"Constructor called for {name}")

    # Destructor (Invoked upon garbage collection)
    def __del__(self):
        print(f"Destructor called for {self.name}")

    def display(self):
        print(f"Name: {self.name}, Age: {self.age}")

# Instantiation (Returns a reference to the heap object)
s1 = Student("Alice", 20)
s1.display()

Key Syntax Comparisons

Example

• Access Specifiers: C++ uses explicit labels (public:, private:), whereas Python assumes all members are public by default but uses prefixing conventions (e.g. _ for protected, __ for private). • this vs self: C++ uses an implicit this pointer pointing to the current object. Python requires passing the instance reference explicitly as the first parameter (traditionally named self) to all instance methods.

Discussion

Join the discussion! Sign in to leave comments and ask questions.

Loading discussion...