C++ · OOP: classes and constructors
Classes with public/private members, constructors with initialiser lists, const member functions, and destructors.
This is the same idea as Python classes, with stricter rules:
private:members can only be reached from inside the class, and the compiler enforces it. Python only has the_nameconvention.- The constructor has the class’s name and no return type. The member initialiser list (
: name_(n)) sets members before the body runs. - A
constmember function promises not to modify the object, so you can call it onconstobjects. - The destructor
~ClassName()runs automatically when the object goes out of scope. I’ll come back to this with RAII.
#include <iostream>
#include <string>
class Student {
public:
Student(std::string name, int marks) : name_(std::move(name)), marks_(marks) {
std::cout << "constructed " << name_ << '\n';
}
~Student() { std::cout << "destroyed " << name_ << '\n'; }
const std::string& name() const { return name_; }
bool passed(int cutoff = 40) const { return marks_ >= cutoff; }
void setMarks(int m) { if (m >= 0 && m <= 100) marks_ = m; }
private:
std::string name_;
int marks_;
};
int main() {
Student a("Sahaj", 88);
{
Student b("Ravi", 35);
std::cout << b.name() << " passed? " << b.passed() << '\n';
} // b destroyed here
a.setMarks(150); // ignored by validation
std::cout << a.name() << " passed? " << a.passed(90) << '\n';
}
Output:
constructed Sahaj
constructed Ravi
Ravi passed? 0
destroyed Ravi
Sahaj passed? 0
destroyed SahajSources
- Classes — cppreference.com
- Constructors and member initializer lists — cppreference.com
- Const class objects and const member functions — LearnCpp.com