C++ Classes and Objects
A class is a plan for a kind of object: it lists the data each object holds and the functions that work on it. An object is one thing made from that plan. std::string is a class; every string variable is an object of it.
Defining a class
#include <iostream>
#include <string>
class Car {
public:
std::string brand;
int year = 0;
int speed = 0;
void accelerate(int amount) {
speed += amount;
}
void describe() const {
std::cout << brand << " (" << year << ") at " << speed << " km/h\n";
}
};
int main() {
Car a;
a.brand = "Tata";
a.year = 2022;
a.accelerate(40);
Car b;
b.brand = "Maruti";
b.year = 2019;
b.accelerate(25);
b.accelerate(30);
a.describe();
b.describe();
return 0;
}Tata (2022) at 40 km/h Maruti (2019) at 55 km/h
- Data members (
brand,year,speed) are the object's data; every object has its own copy. - Member functions (
accelerate,describe) work on the object they are called on, with a dot:a.accelerate(40). constafterdescribe()promises that it only reads the object.- A class definition ends with
};, with a semicolon.
public and private
Members under public: can be used from anywhere; members under private: only by the class's own functions. Class members are private by default. Good classes keep their data private and offer public functions:
#include <iostream>
#include <string>
class Student {
private:
std::string name;
int marks = 0;
public:
void setName(const std::string& n) { name = n; }
void setMarks(int m) {
if (m >= 0 && m <= 100) marks = m; // the class checks the value
}
std::string getName() const { return name; }
int getMarks() const { return marks; }
};
int main() {
Student s;
s.setName("Asha");
s.setMarks(84);
s.setMarks(150); // refused: outside 0 to 100
std::cout << s.getName() << ": " << s.getMarks() << "\n";
return 0;
}Asha: 84
Functions like setMarks and getMarks are called setters and getters. The setter can refuse wrong values, so a Student can never hold impossible marks.
Objects in a vector
#include <iostream>
#include <string>
#include <vector>
class Item {
public:
std::string name;
double price = 0;
int qty = 0;
double total() const { return price * qty; }
};
int main() {
std::vector<Item> cart = {{"Pen", 10, 3}, {"Notebook", 45, 2}};
double sum = 0;
for (const Item& it : cart) {
std::cout << it.name << ": " << it.total() << "\n";
sum += it.total();
}
std::cout << "Cart total: " << sum << "\n";
return 0;
}Pen: 30 Notebook: 90 Cart total: 120
Class or struct?
class and struct differ only in the default: members of a class are private unless you write public:, members of a struct are public. By convention, struct is used for plain groups of data and class for types that protect their data and have rules, like Student above.
Practice exercises
- Write a
Rectangleclass with width and height and member functionsareaandperimeter. - Make the members private and add setters that refuse negative sizes.
- Store three rectangles in a vector and print the one with the largest area.