⚡0 XP🔥0

Classes and Objects

Lesson 4 of 12 ⏱ 6 min read ✎ 2 exercises ❓ 5-question quiz ▶ Runs C++

The four pillars of OOP, defining a class, creating objects, access specifiers (public/private), member functions, the this pointer, static members and friend functions.

Object-oriented programming#

In procedural C, data (structs) and the functions that use it are separate. Object-oriented programming (OOP) puts them together into objects. A bank account object holds its balance and knows how to deposit and withdraw.

The four pillars of OOP:

Pillar Idea C++ feature
Encapsulation keep data and its functions together; hide the internals class, private, public
Abstraction show what an object does, hide how public interface, abstract classes
Inheritance build new classes from existing ones class Car : public Vehicle
Polymorphism one interface, many forms overloading, virtual functions
हिंदी में समझें

Class एक नक्शा (blueprint) है - जैसे मकान का नक्शा। Object उस नक्शे से बना असली मकान है। एक class से कितने भी objects बना सकते हैं, और हर object का अपना data होता है (हर मकान का अपना रंग, अपने लोग)।

Defining a class#

class Student {
private:              // only member functions can touch these
    string name;
    int marks;
public:               // anyone can call these
    void setData(string n, int m);
    void show();
};
▶ Try it YourselfC++
Ctrl + Enter to run
Output
Kavya scored 92 (grade A)
Harsh scored 0 (grade F)

Because marks is private, the only way to set it is through setData, which validates it. That is encapsulation: the class protects its own data.

Access specifiers#

Specifier Accessible from
public anywhere
private only inside the class (and friends)
protected inside the class and its derived (child) classes
Note

class and struct are almost identical in C++. The only difference: members are private by default in a class and public by default in a struct. Use struct for plain data, class for objects with behaviour.

Getters and setters, and const member functions#

▶ Try it YourselfC++
Ctrl + Enter to run
Output
36.6 C = 97.88 F
Clamped to -273.15

A const after the parameter list promises the function does not change the object - and lets it be called on const objects.

Defining member functions outside the class#

In bigger programs the class declaration goes in a .h file and function bodies in a .cpp file, using the scope resolution operator :::

▶ Try it YourselfC++
Ctrl + Enter to run
Output
Area: 12.5664

The this pointer#

Inside a member function, this points to the object the function was called on. It is handy when a parameter has the same name as a member, and for method chaining:

▶ Try it YourselfC++
Ctrl + Enter to run
Output
5 x Notebook

Static members#

A static data member belongs to the class, not to any one object - all objects share it. A static member function can be called with ClassName::function():

▶ Try it YourselfC++
Ctrl + Enter to run
Output
Ticket #1001 - Asha
Ticket #1002 - Imran
Ticket #1003 - Priya
Tickets issued: 3

Friend functions#

A friend function is not a member, but is allowed to access private members. Use it sparingly - for example when a function needs the internals of two different classes:

▶ Try it YourselfC++
Ctrl + Enter to run
Output
First box is wider

(Box(double w) : width(w) {} is a constructor - covered in the next lesson.)

Summary#

  • A class bundles data members and member functions; objects are instances of a class.
  • private data + public methods = encapsulation; validate data inside setters.
  • Mark read-only methods const; define methods outside with ClassName::.
  • this points to the current object; static members are shared; friends can see private members.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Rectangle class

Create a class Rectangle with private length and width, a public set(double l, double w), and public area() and perimeter(). For a 7.5 × 4 rectangle print:

Area: 30
Perimeter: 23
Expected output:
Area: 30
Perimeter: 23
2

Counting objects with static

Give the class Student a static int count that increases every time enroll() is called on any student, and a static function total() that returns it. After enrolling three students print Total enrolled: 3.

Expected output:
Total enrolled: 3

Quick Quiz

Q1.

What is the default access level of class members?

Q2.

An object is...

Q3.

What does this point to inside a member function?

Q4.

A static data member is...

Q5.

Which OOP principle hides internal data behind public methods?