LearnFrenzy
Sign in Take a free test

C++ Programming · Topic 9 of 27

Classes and Objects

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Coding Techniques

Classes and Objects · Study material

Give your class an operator<< for printing

A friend operator<< lets objects be printed with cout like built-in types, and keeps formatting logic inside the class. Return the stream so outputs can be chained.

#include <iostream>
#include <string>

class Money {
    long long paise_;
public:
    explicit Money(long long paise) : paise_(paise) {}
    Money operator+(const Money& o) const { return Money(paise_ + o.paise_); }
    friend std::ostream& operator<<(std::ostream& os, const Money& m) {   // makes cout << m work
        return os << "Rs " << m.paise_ / 100 << '.' << (m.paise_ % 100 < 10 ? "0" : "") << m.paise_ % 100;
    }
};

int main() {
    Money fee(149900), tax(26982);
    std::cout << fee << " + " << tax << " = " << fee + tax << '\n';
    return 0;
}

Output

Rs 1499.00 + Rs 269.82 = Rs 1768.82

Keep data private and expose intent-revealing functions

// Getter/setter for everything: callers still manipulate raw data
class Order {
public:
    void set_status(int s);      // what do 0, 1, 2 mean? who checks transitions?
};

// Behaviour-based interface: the class owns its rules
class Order {
    enum class Status { placed, shipped, delivered } status_ = Status::placed;
public:
    bool ship()    { if (status_ != Status::placed) return false; status_ = Status::shipped; return true; }
    bool deliver() { if (status_ != Status::shipped) return false; status_ = Status::delivered; return true; }
    bool delivered() const { return status_ == Status::delivered; }
};

Use default member initializers

class Settings {
    int volume_ = 50;            // every constructor starts from these values
    bool muted_ = false;
    std::string theme_ = "light";
public:
    Settings() = default;
    explicit Settings(int volume) : volume_(volume) {}   // overrides only what it needs
};

No member can be left uninitialized by a forgotten constructor, and each constructor lists only what differs.

Make const-correctness a habit

class Account {
public:
    double balance() const;                      // query: const
    const std::string& owner() const;            // return large members by const&
    void deposit(double amount);                 // command: non-const
};

void report(const Account& a) {                  // accept const& …
    std::cout << a.owner() << ": " << a.balance();   // … and only const members can be called
}

Good class-design habits

  • One responsibility per class; keep classes small.
  • Data members private, with trailing underscores or another consistent naming style.
  • Initialize every member – with default member initializers or the initializer list.
  • Mark queries const; return large members by const&.
  • Declare in the header, define longer functions in the .cpp file.
  • Use struct for plain data aggregates and = default comparisons.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C++ Programming

C++ adds object-oriented programming, templates and the powerful Standard Template Library (STL) to C. It powers game engines, browsers, trading systems and most competitive programming. This section takes you from basic syntax to classes, inheritance, polymorphism, modern C++ (C++11 to C++23) and the STL – every concept with runnable examples and practice questions checked on a real compiler.

Why it matters

  • OOP concepts – classes, inheritance, polymorphism, encapsulation – are asked in almost every interview
  • C++ with the STL is the most popular language for competitive programming and DSA rounds
  • Questions on constructors, virtual functions, references and smart pointers decide technical rounds
  • Modern C++ skills are in demand at product companies, fintech and game studios

Who it is for

  • School students (Class 11–12 computer science with C++) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA) learning OOP and data structures for semester exams and labs
  • Freshers preparing for placements, coding tests and C++ technical interviews
  • Competitive programmers who want to master the STL

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Product company interviews
  • Coding rounds & DSA
  • Competitive programming
  • GATE CS
  • University exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links