C++ Classes and Objects Tutorial
Classes and objects are fundamental concepts of Object-Oriented Programming (OOP) in C++. Classes are blueprints, and objects are instances of these classes.
What is a Class?
A class defines properties and behaviors using members like attributes (variables) and methods (functions).
#include <iostream>
using namespace std;
class Car {
public:
string brand;
int year;
void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};
What is an Object?
An object is an instance of a class that holds data and interacts with other objects.
int main() {
Car car1; // Create object
car1.brand = "Toyota"; // Set attributes
car1.year = 2020;
car1.display(); // Call method
return 0;
}
Constructor in Classes
Constructors are special methods called when an object is created. They initialize object attributes.
class Car {
public:
string brand;
int year;
Car(string b, int y) { // Constructor
brand = b;
year = y;
}
void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};
int main() {
Car car1("Honda", 2019);
car1.display();
return 0;
}
Access Specifiers
Access specifiers define the accessibility of class members:
public: Accessible from outside the class.private: Accessible only within the class.protected: Accessible within the class and derived classes.
class Person {
private:
string name;
public:
void setName(string n) {
name = n;
}
string getName() {
return name;
}
};
Member Functions
Member functions are functions defined inside or outside the class to operate on its data members.
class Rectangle {
private:
int width, height;
public:
void setDimensions(int w, int h) {
width = w;
height = h;
}
int area() {
return width * height;
}
};
int main() {
Rectangle rect;
rect.setDimensions(5, 10);
cout << "Area: " << rect.area() << endl;
return 0;
}
×