Classes, Objects, and Constructors in C++ and Python
Learn class declarations, object instantiation, and constructor behaviors in C++ and Python side-by-side.
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
#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
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
• 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.