WikiGalaxy

Personalize

C++ Classes and Objects

Introduction to Classes

A class in C++ is a blueprint for creating objects. It encapsulates data for the object and methods to manipulate that data.

Defining a Class

A class is defined using the class keyword followed by the class name and a body enclosed in curly braces.

Creating an Object

An object is an instance of a class. It is created by declaring it with the class type.

Access Modifiers

Access modifiers define the access level of class members. C++ has three: public, private, and protected.

Constructors

Constructors are special member functions used to initialize objects. They have the same name as the class.

Destructors

Destructors are used to release resources allocated to an object. They have the same name as the class prefixed with a tilde (~).


class Car {
  public:
    string brand;
    string model;
    int year;
    Car(string x, string y, int z) {
      brand = x;
      model = y;
      year = z;
    }
};

// Create an object of Car
Car carObj1("Toyota", "Corolla", 2015);
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year;
    

Methods in Classes

Methods are functions defined inside a class. They operate on the data contained in the object.

Static Members

Static members are shared among all objects of a class. They can be accessed using the class name.

Friend Functions

Friend functions have access to private and protected members of a class. They are not member functions.

Inheritance

Inheritance allows a class to inherit properties and methods from another class. It promotes code reusability.

Polymorphism

Polymorphism allows methods to do different things based on the object it is acting upon. It is implemented using function overloading and overriding.

Encapsulation

Encapsulation is the bundling of data and methods that operate on the data within a single unit or class.

Console Output:

Toyota Corolla 2015

Class Constructors and Destructors

Purpose of Constructors

Constructors are used to initialize objects. They set initial values for object attributes.

Types of Constructors

There are three types of constructors: default, parameterized, and copy constructors.

Destructor Functionality

Destructors clean up resources that an object may have acquired during its lifetime.

Automatic Invocation

Constructors and destructors are automatically called when an object is created and destroyed, respectively.


class Rectangle {
  public:
    int width, height;
    Rectangle(int w, int h) {
      width = w;
      height = h;
    }
    ~Rectangle() {
      cout << "Rectangle destroyed";
    }
};

Rectangle rect(10, 20);
cout << rect.width << " " << rect.height;
    

Constructor Overloading

Multiple constructors can be defined with different parameters to initialize objects in different ways.

Destructor Limitations

Destructors cannot be overloaded and do not take parameters. They are called once per object.

Console Output:

10 20

Rectangle destroyed

Inheritance in C++

Concept of Inheritance

Inheritance allows one class to inherit members and behaviors from another class, promoting code reusability.

Base and Derived Classes

The class that is inherited from is called the base class, and the class that inherits is called the derived class.

Types of Inheritance

C++ supports several types of inheritance: single, multiple, multilevel, hierarchical, and hybrid inheritance.

Access Control in Inheritance

Access control determines how members of the base class can be accessed by the derived class.


class Animal {
  public:
    void eat() {
      cout << "Eating";
    }
};

class Dog : public Animal {
  public:
    void bark() {
      cout << "Barking";
    }
};

Dog myDog;
myDog.eat();
myDog.bark();
    

Virtual Inheritance

Virtual inheritance is used to solve the diamond problem in multiple inheritance scenarios.

Constructor and Destructor Calls

Constructors and destructors of base and derived classes are called in a specific order during object creation and destruction.

Console Output:

Eating

Barking

Polymorphism in C++

Understanding Polymorphism

Polymorphism allows methods to perform different tasks based on the object calling them.

Compile-Time Polymorphism

Also known as static binding, it is achieved through function overloading and operator overloading.

Run-Time Polymorphism

Also known as dynamic binding, it is achieved through virtual functions and inheritance.

Virtual Functions

Virtual functions allow derived classes to override methods of the base class, enabling dynamic method resolution.


class Base {
  public:
    virtual void show() {
      cout << "Base class";
    }
};

class Derived : public Base {
  public:
    void show() override {
      cout << "Derived class";
    }
};

Base* b;
Derived d;
b = &d;
b->show();
    

Pure Virtual Functions

A pure virtual function is declared by assigning 0 to it and makes a class abstract.

Abstract Classes

Classes containing pure virtual functions are abstract and cannot be instantiated.

Console Output:

Derived class

Encapsulation in C++

Definition of Encapsulation

Encapsulation is the bundling of data and methods that work on that data within a single unit.

Benefits of Encapsulation

It helps protect the internal state of an object and only allows manipulation through methods.

Getters and Setters

Getters and setters are methods used to access and update private data members of a class.

Data Hiding

Encapsulation helps in hiding the internal implementation details of a class from the outside world.


class Employee {
  private:
    int salary;
  public:
    void setSalary(int s) {
      salary = s;
    }
    int getSalary() {
      return salary;
    }
};

Employee emp;
emp.setSalary(50000);
cout << emp.getSalary();
    

Interface Design

Encapsulation is crucial for designing robust interfaces and ensuring that objects are used in a controlled manner.

Improved Maintainability

By hiding complexities, encapsulation makes code easier to maintain and modify.

Console Output:

50000

Operator Overloading

Concept of Operator Overloading

Operator overloading allows operators to be redefined and used in different ways, particularly with user-defined types.

Syntax for Overloading

Operators are overloaded by defining a function with the operator keyword followed by the operator symbol.

Commonly Overloaded Operators

Common operators that can be overloaded include +, -, *, /, ==, and [] among others.

Limitations of Overloading

Not all operators can be overloaded. For instance, the scope resolution (::) and member selection (.) operators cannot.


class Complex {
  private:
    int real, imag;
  public:
    Complex(int r = 0, int i = 0) { real = r; imag = i; }
    Complex operator + (Complex const &obj) {
      Complex res;
      res.real = real + obj.real;
      res.imag = imag + obj.imag;
      return res;
    }
    void display() { cout << real << " + i" << imag; }
};

Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
c3.display();
    

Overloading Binary Operators

Binary operators require two operands and are overloaded by defining a member function with one parameter.

Overloading Unary Operators

Unary operators take a single operand and are overloaded by defining a member function with no parameters.

Console Output:

12 + i9

Friend Functions

Role of Friend Functions

Friend functions allow access to private and protected members of a class from outside the class.

Defining Friend Functions

Friend functions are declared using the friend keyword inside the class definition.

Advantages of Friend Functions

They provide more flexibility in designing interfaces that need access to class internals.

Limitations of Friend Functions

Excessive use of friend functions can break the encapsulation principle of object-oriented programming.


class Box {
  private:
    int width;
  public:
    Box(int w) : width(w) {}
    friend void printWidth(Box b);
};

void printWidth(Box b) {
  cout << "Width of box: " << b.width;
}

Box box(10);
printWidth(box);
    

Friend Classes

Entire classes can be declared as friends, allowing all member functions of the friend class to access private members of the befriended class.

Friendship is Not Inherited

Friendship is not inherited, meaning derived classes do not inherit the friend status of their base class.

Console Output:

Width of box: 10

Templates in C++

Understanding Templates

Templates allow functions and classes to operate with generic types, making them flexible and reusable.

Function Templates

Function templates enable functions to work with different data types without being rewritten for each type.

Class Templates

Class templates allow classes to handle any data type, providing a way to create generic classes.

Template Syntax

Templates are defined using the template keyword followed by template parameters in angle brackets.


template 
T add(T a, T b) {
  return a + b;
}

cout << add(3, 4);
cout << add(3.5, 4.5);
    

Specialization of Templates

Template specialization provides a way to define different implementations of a template for specific data types.

Non-Type Template Parameters

Templates can also accept non-type parameters, allowing more flexibility in template usage.

Console Output:

7

8

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025