Classes & Objects
Classes & Objects
Define a class with data members and member functions, create objects, control access with public and private, and define methods outside the class with ::.
Defining a class
#include <iostream>
#include <string>
using namespace std;
class Student {
public: // accessible from anywhere
string name;
int roll;
double marks[3];
double average() { // member function (method)
return (marks[0] + marks[1] + marks[2]) / 3;
}
void print() {
cout << roll << " " << name << " avg " << average() << endl;
}
}; // note the semicolon!
int main() {
Student s1; // create an object
s1.name = "Asha";
s1.roll = 7;
s1.marks[0] = 88; s1.marks[1] = 92; s1.marks[2] = 79;
s1.print();
Student s2 = s1; // copy: s2 has its own data
s2.name = "Ravi";
s2.roll = 8;
s1.print();
s2.print();
return 0;
}7 Asha avg 86.3333 7 Asha avg 86.3333 8 Ravi avg 86.3333
Each object has its own copy of the data members; member functions are shared by all objects of the class.
Access specifiers
| Specifier | Accessible from |
|---|---|
public |
anywhere |
private |
only inside the class (and its friends) |
protected |
inside the class and classes derived from it |
In a class, members are private by default. In a struct, they are public by default — that is the only difference between the two in C++.
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance = 0; // hidden: no one outside can set it to -1000
public:
void deposit(double amount) {
if (amount > 0) balance += amount;
}
bool withdraw(double amount) {
if (amount <= 0 || amount > balance) return false;
balance -= amount;
return true;
}
double getBalance() { return balance; }
};
int main() {
BankAccount acc;
acc.deposit(5000);
cout << "withdraw 7000: " << (acc.withdraw(7000) ? "ok" : "refused") << endl;
cout << "withdraw 1200: " << (acc.withdraw(1200) ? "ok" : "refused") << endl;
cout << "balance: " << acc.getBalance() << endl;
// acc.balance = 1000000; // error: 'balance' is a private member
return 0;
}withdraw 7000: refused withdraw 1200: ok balance: 3800
Defining methods outside the class
For longer methods, declare them inside the class and define them outside using the scope resolution operator ::. This is how real projects split code between a header (.h) and a source file (.cpp).
#include <iostream>
using namespace std;
class Rectangle {
double length, width;
public:
void set(double l, double w);
double area();
double perimeter();
};
void Rectangle::set(double l, double w) { length = l; width = w; }
double Rectangle::area() { return length * width; }
double Rectangle::perimeter() { return 2 * (length + width); }
int main() {
Rectangle r;
r.set(7, 3);
cout << "area " << r.area() << ", perimeter " << r.perimeter() << endl;
return 0;
}area 21, perimeter 20
Arrays of objects and objects as arguments
#include <iostream>
#include <string>
using namespace std;
class Item {
public:
string name;
int qty;
double price;
double total() const { return qty * price; }
};
double billTotal(const Item items[], int n) {
double sum = 0;
for (int i = 0; i < n; i++) sum += items[i].total();
return sum;
}
int main() {
Item cart[3] = {{"Notebook", 4, 45.0}, {"Pen", 10, 12.5}, {"Geometry box", 1, 180.0}};
for (const Item &it : cart)
cout << it.name << " x" << it.qty << " = " << it.total() << endl;
cout << "Bill: Rs " << billTotal(cart, 3) << endl;
return 0;
}Notebook x4 = 180 Pen x10 = 125 Geometry box x1 = 180 Bill: Rs 485
Memory for objects
sizeof an object counts only its data members (plus padding). Member functions are stored once, in the code, not inside each object:
#include <iostream>
using namespace std;
class Point {
int x, y;
public:
void move(int dx, int dy) { x += dx; y += dy; }
int getX() { return x; }
};
int main() {
cout << "sizeof(Point) = " << sizeof(Point) << " bytes (two ints)" << endl;
return 0;
}sizeof(Point) = 8 bytes (two ints)
Test yourself
4 questions · pick an answer to check it instantly
- 1
What is the default access level of members in a
class?Class members are private unless you say otherwise; struct members are public. - 2
What does
::do indouble Rectangle::area()?The scope resolution operator ties the definition to the class. - 3
Two objects of the same class...
Data is per object; code is shared. - 4
Which line would fail to compile for the
BankAccountclass?balanceis private, so code outside the class cannot touch it.