All Courses
OOP: CLASSES AND OBJECTS

Class Definition

In C++, a class is defined using the class keyword.

General Syntax

class ClassName {
private:
    // data members

public:
    // member functions
};

Important: the class definition must end with a semicolon.

Example

#include <iostream>
#include <string>

class Book {
private:
    std::string title;
    std::string author;

public:
    void setDetails(const std::string& bookTitle, const std::string& bookAuthor) {
        title = bookTitle;
        author = bookAuthor;
    }

    void display() const {
        std::cout << title << " by " << author << '\n';
    }
};

int main() {
    Book book;
    book.setDetails("Effective C++", "Scott Meyers");
    book.display();
}

Parts of a Class

Class Name

The name of the new type.

class Book

By convention, class names often start with a capital letter.

Private Section

The private section stores details that outside code should not directly touch.

private:
    std::string title;

Public Section

The public section exposes what outside code can use.

public:
    void display() const;

Data Members

Variables inside a class.

Member Functions

Functions inside a class.

Default Access

In a class, members are private by default.

class Demo {
    int value; // private by default
};

You will study access specifiers deeply in Chapter 5. For now, remember this rule.

Common Syntax Mistake

Wrong:

class Student {
}

Correct:

class Student {
};

Viva Answer

A class is defined with the class keyword, a class name, a body containing data members and member functions, and a required semicolon after the closing brace. In a C++ class, members are private by default.

Quick Check

  • Which keyword defines a class?
  • Why is the semicolon after } required?
  • What is private by default in a class?
  • What is the difference between data member and member function?