Software Development Exam  >  Software Development Notes  >  DSA in C++  >  Object Oriented Programming in C++

Object Oriented Programming in C++ | DSA in C++ - Software Development PDF Download

Introduction

Object-oriented programming (OOP) is a popular programming paradigm that allows us to organize code in a modular and structured manner. In this article, we will explore the fundamentals of object-oriented programming in C++. We will cover the basic concepts of classes and objects, encapsulation, inheritance, and polymorphism. Along the way, we'll provide multiple examples and simple code snippets to illustrate each concept.

Classes and Objects

In C++, a class is a blueprint for creating objects, while an object is an instance of a class. A class defines the properties (attributes) and behaviors (methods) that an object can have. Let's look at a simple example of a class representing a student:

class Student {

  public:

    // Attributes

    string name;

    int age;

    

    // Methods

    void displayInfo() {

        cout << "Name: " << name << endl;

        cout << "Age: " << age << endl;

    }

};

In the code above, we define a 'Student' class with two attributes ('name' and 'age') and a method ('displayInfo') that displays the student's information. To create an object of this class, we can do the following:

int main() {

  // Create an object of the Student class

  Student student1;

  

  // Assign values to attributes

  student1.name = "John";

  student1.age = 20;

  

  // Call the displayInfo method

  student1.displayInfo();

  

  return 0;

}

Output:

Name: John

Age: 20

In the example above, we create an object 'student1' of the 'Student' class, assign values to its attributes, and call the 'displayInfo' method to display the student's information.

Encapsulation

Encapsulation is the principle of bundling data (attributes) and methods (behaviors) together within a class. It helps in hiding the internal implementation details of a class and provides a clear interface for interacting with objects. Let's extend our 'Student' class to demonstrate encapsulation:

class Student {

  private:

    string name;

    int age;


  public:

    // Setter methods

    void setName(string studentName) {

        name = studentName;

    }


    void setAge(int studentAge) {

        age = studentAge;

    }


    // Getter methods

    string getName() {

        return name;

    }


    int getAge() {

        return age;

    }


    void displayInfo() {

        cout << "Name: " << name << endl;

        cout << "Age: " << age << endl;

    }

};

In the modified code, we have made the 'name' and 'age' attributes private. We provide public setter and getter methods ('setName', 'setAge', 'getName', and 'getAge') to access and modify these private attributes. Now, let's update our 'main' function to use the setter and getter methods:

int main() {

  Student student1;

  

  // Use setter methods to assign values

  student1.setName("John");

  student1.setAge(20);

  

  // Use getter methods to retrieve values

  cout << "Name: " << student1.getName() << endl;

  cout << "Age: " << student1.getAge() << endl;

  

  return 0;

}

Output:

Name: John

Age: 20

In the updated code, we use the setter methods to assign values to the private attributes of the 'student1' object and the getter methods to retrieve those values. Encapsulation helps maintain data integrity and provides controlled access to class members.

Inheritance

Inheritance is a mechanism that allows a class to inherit properties and behaviors from another class. The class that is being inherited from is called the base class or parent class, and the class that inherits is called the derived class or child class. Let's illustrate inheritance with an example:

// Base class

class Shape {

  protected:

    int width;

    int height;


  public:

    void setDimensions(int w, int h) {

        width = w;

        height = h;

    }

};


// Derived class

class Rectangle : public Shape {

  public:

    int getArea() {

        return width * height;

    }

};

In the code above, we have a base class 'Shape' with two protected attributes ('width' and 'height') and a method 'setDimensions' to set the dimensions of a shape. The derived class 'Rectangle' inherits from the 'Shape' class and adds its own method 'getArea' to calculate the area of a rectangle. Let's create a 'Rectangle' object and calculate its area:

int main() {

  Rectangle rect;

  

  rect.setDimensions(5, 7);

  int area = rect.getArea();

  

  cout << "Area: " << area << endl;

  

  return 0;

}

Output:

Area: 35

In the above code, we create a 'Rectangle' object 'rect', set its dimensions using the 'setDimensions' method inherited from the Shape class, and calculate the area using the 'getArea' method defined in the 'Rectangle' class. Inheritance allows us to reuse code and create specialized classes based on existing ones.

Polymorphism

Polymorphism is the ability of objects of different classes to respond uniquely to the same message or method call. It allows us to write more flexible and extensible code. Let's understand polymorphism with an example:

// Base class

class Shape {

  public:

    virtual void displayInfo() {

        cout << "This is a shape." << endl;

    }

};


// Derived class

class Rectangle : public Shape {

  public:

    void displayInfo() override {

        cout << "This is a rectangle." << endl;

    }

};


// Derived class

class Circle : public Shape {

  public:

    void displayInfo() override {

        cout << "This is a circle." << endl;

    }

};

In the code above, we have a base class 'Shape' with a virtual method 'displayInfo'. The derived classes 'Rectangle' and 'Circle' override this method to provide their own implementation. Let's create an array of shape objects and invoke the 'displayInfo' method:

int main() {

  Shape* shapes[2];

  

  shapes[0] = new Rectangle();

  shapes[1] = new Circle();

  

  for (int i = 0; i < 2; i++) {

      shapes[i]->displayInfo();

  }

  

  return 0;

}

Output:

This is a rectangle.

This is a circle.

In the example above, we create an array of shape pointers and assign a 'Rectangle' and a 'Circle' object to those pointers. By calling the 'displayInfo' method on each object, we see different outputs based on their respective implementations. Polymorphism allows us to treat objects of different classes as objects of a common base class, enabling flexibility and code reuse.

Sample Problems and Solutions

Here are a few sample problems to test your understanding of object-oriented programming in C++:

Problem 1: Create a class 'Car' with attributes 'brand', 'model', and 'year'. Implement a method 'displayInfo' to display the car's information.

class Car {

  public:

    string brand;

    string model;

    int year;

    

    void displayInfo() {

        cout << "Brand: " << brand << endl;

        cout << "Model: " << model << endl;

        cout << "Year: " << year << endl;

    }

};


int main() {

  Car car1;

  

  car1.brand = "Toyota";

  car1.model = "Camry";

  car1.year = 2020;

  

  car1.displayInfo();

  

  return 0;

}

Output:

Brand: Toyota

Model: Camry

Year: 2020

Problem 2: Create a class 'BankAccount' with attributes 'accountNumber' and 'balance'. Implement methods 'deposit' and 'withdraw' to modify the account balance.

class BankAccount {

  private:

    int accountNumber;

    double balance;


  public:

    BankAccount(int accNum, double initBalance) {

        accountNumber = accNum;

        balance = initBalance;

    }


    void deposit(double amount) {

        balance += amount;

    }


    void withdraw(double amount) {

        if (amount <= balance) {

            balance -= amount;

        } else {

            cout << "Insufficient balance." << endl;

        }

    }


    void displayBalance() {

        cout << "Account Number: " << accountNumber << endl;

        cout << "Balance: " << balance << endl;

    }

};


int main() {

  BankAccount account(12345, 1000);

  

  account.deposit(500);

  account.withdraw(200);

  account.displayBalance();

  

  return 0;

}

Output:

Account Number: 12345

Balance: 1300

Conclusion

In this article, we covered the basics of object-oriented programming in C++. We learned about classes and objects, encapsulation, inheritance, and polymorphism. By understanding these core concepts, you'll be well-equipped to write clean, modular, and maintainable code using the power of object-oriented programming in C++.

The document Object Oriented Programming in C++ | DSA in C++ - Software Development is a part of the Software Development Course DSA in C++.
All you need of Software Development at this link: Software Development
153 videos|115 docs|24 tests

Top Courses for Software Development

153 videos|115 docs|24 tests
Download as PDF
Explore Courses for Software Development exam

Top Courses for Software Development

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

Free

,

MCQs

,

Important questions

,

practice quizzes

,

video lectures

,

Extra Questions

,

Object Oriented Programming in C++ | DSA in C++ - Software Development

,

Semester Notes

,

Viva Questions

,

Previous Year Questions with Solutions

,

Object Oriented Programming in C++ | DSA in C++ - Software Development

,

mock tests for examination

,

past year papers

,

pdf

,

Sample Paper

,

Object Oriented Programming in C++ | DSA in C++ - Software Development

,

Exam

,

shortcuts and tricks

,

Objective type Questions

,

ppt

,

study material

,

Summary

;