programs of oops in c++

 

Inheritance

 

Single level inheritance:

 

#include <iostream> 

using namespace std; 

 class Account { 

   public: 

   int a=8;

   int b=56;   

}; 

 

class Programmer: public Account { 

            public: 

            void display(){

            cout<<a+b;

   } 

};      

int main() { 

    Programmer p1; 

    p1.display();

    return 0; 

} 

 

 

#include <iostream> 

using namespace std; 

class A 

{ 

    int a = 4; 

    int b = 5; 

    public: 

    int mul() 

    { 

        int c = a*b; 

        return c; 

    }    

}; 

 

class B : private A 

{ 

    public: 

    void display() 

    { 

        int result = mul(); 

        std::cout <<"Multiplication of a and b is : "<<result<< std::endl; 

    } 

}; 

int main() 

{ 

   B b; 

   b.display(); 

 

    return 0; 

} 

 

Multilevel inheritance

 

#include <iostream> 

using namespace std; 

class A { 

            public:

                        int a;

                        int b;

   public: 

            void Display() {  

    cout<<"the value of a is:"; 

            cin>>a;

    cout<<"the value of b is:";

            cin>>b;

            }   

}; 

class B: public A  

{   

    public: 

    void Show(){ 

    cout<<"The addition of a and b is:"<<a+b<<endl;  

    }   

};  

class C: public B  

   {   

    public: 

    void Show1() { 

    cout<<"The subtraction of a and b is:"<<a-b;  

     }    

   };  

int main() { 

    C obj; 

    obj.Display(); 

    obj.Show(); 

    obj.Show1(); 

    return 0; 

}

 

 

Multiple inheritance

 

#include <iostream>

using namespace std;

 

class A {

  public:

            int a;

            int b;

            void display(){

                        cout<<"value of a is:";

                        cin>>a;

                        cout<<"value of b is:";

                        cin>>b;

              }

};

 

class B {

            public:

            int c;

            int d;

  public:

    void Show() {

      cout<<"value of c is:";

              cin>>c;

              cout<<"value of d is:";

              cin>>d;

    }

};

 

class C: public A, public B {

            public:

                        void Show1(){

                                    cout<<"Multiplication of a and b is:"<<a*b<<endl;

                                    cout<<"substraction of c and d is:"<<c-d<<endl;

            }

           

};

 

int main() {

  C Obj;

  Obj.display();

  Obj.Show();

  Obj.Show1();

  return 0;

}

 

 

 

Hierarchical inheritance

 

#include<iostream>

using namespace std;

 

class A

{

public:

void show() {

            cout<<"Hi i am base class"<<endl;

}

};

class B : public A

{

public:

void show1() {

            cout<<"hi i am derived class"<<endl;

}

};

 

class C : public A 

{

public:

void show2() {

            cout<<"hi i am also a derived class"<<endl;

}

};

 

int main() {

B b; 

cout<<"calling from class B: "<<endl;

b.show();

b.show1();

cout<<endl;

           

C c;

cout<<"calling from class C: "<<endl;

c.show();

c.show2();

return 0;

}

 

#include <iostream>

using namespace std;

 

class A {

public:

    int a;

    int b;

 

    void show() {

        cout << "Enter the first value: ";

        cin >> a;

        cout << "Enter the second value: ";

        cin >> b;

    }

};

 

class B : public A {

public:

    void show1() {

        int fact = 1; // Initialize fact inside the method

        for (int i = 1; i <= a; i++) {

            fact *= i;

        }

        cout << "Factorial of " << a << " is: " << fact << endl;

    }

};

 

class C : public A {

public:

    void show2() {

        cout << "Sum of a and b is: " << a + b << endl; // Fixed logical error in the message

    }

};

 

int main() {

    B b;

    cout << "Calling from class B: " << endl;

    b.show();

    b.show1();

    cout << endl;

 

    C c;

    cout << "Calling from class C: " << endl;

    c.show();

    c.show2();

 

    return 0;

}

#include <iostream>

using namespace std;

 

class A {

public:

    int a;

    int b;

 

    void show() {

        cout << "Enter the first value: ";

        cin >> a;

        cout << "Enter the second value: ";

        cin >> b;

    }

};

 

class B : public A {

public:

    void show1() {

        int fact = 1;

        for (int i = 1; i <= a; i++) {

            fact *= i;

        }

        cout << "Factorial of " << a << " is: " << fact << endl;

    }

 

    void show2() {

        int fact = 1;

        for (int i = 1; i <= b; i++) {

            fact *= i;

        }

        cout << "Factorial of " << b << " is: " << fact << endl;

    }

};

 

class C : public A {

public:

    void show3() {

        cout << "Sum of a and b is: " << a + b << endl;

    }

};

 

int main() {

    B b;  

    b.show();

    b.show1();

    b.show2();

    cout << endl;

 

    C c;

    c.show();

    c.show3();

 

    return 0;

}

 

hybrid inheritance

 

 

#include <iostream>

using namespace std;

 

class A {

public:

    int a;

    int b;

    void displayA() {

        cout << "The value of a:";

        cin>>a;

        cout << "The value of b:";

        cin>>b;

    }

};

class B : public A {

public:

    void displayB() {

        cout <<"The multiplication of a and b is:"<<a*b << endl;

    }

};

 

class C {

public:

    int c;

    int d;

    void displayC() {

        cout << "The value of c:";

        cin>>c;

        cout << "The value of d:";

        cin>>d;

        cout << "Sum of c and d:" <<c+d<< endl;

    }

};

 

class D : public B, public C {

public:

    void displayD() {

        cout << "the total of class B and class C:"<<(a*b)+(c+d) << endl;

    }

};

 

int main() {

    D obj;

 

    obj.displayA();

    obj.displayB();

    obj.displayC();

    obj.displayD();

    return 0;

}

 

Polymorphism...................

 

function Overloading

 

#include <iostream>

using namespace std;

 

class Calculator {

public:

    int add(int a, int b) {

        return a + b;

    }

 

    int add(int a, int b, int c) {

        return a + b + c;

    }

 

    double add(double a, double b) {

        return a + b;

    }

};

 

int main() {

    Calculator calc;

 

    cout << calc.add(3, 5) << endl;

    cout << calc.add(1, 2, 3) << endl;

    cout << calc.add(2.5, 3.5) << endl;

 

    return 0;

}

 

Operator Overloading

           

#include <iostream> 

using namespace std; 

 

class Test 

{ 

   private: 

      int num; 

 

   public: 

  

       Test(int n) 

       {

           num = n;

       }

 

       void operator ++()        

       {  

           num = num + 2;  

       } 

 

       void Print()

       {  

           cout << "The Count is: " << num;  

       } 

}; 

 

int main() 

{ 

    Test tt(8);    

    ++tt;          

    tt.Print();    

    return 0; 

} 

 

 

Runtime Polymorphism

 

#include <iostream>

using namespace std;

 

class A {

public:

    void Print()

    {

        cout << "Hi" << endl;

    }

};

 

class B : public A {

public:

    void Print()

    {

        cout << "My name is Astha Kathayat" << endl;

 

        A::Print();

    }

};

 

int main()

{

    B obj;

    obj.Print();

    return 0;

}

 

Virtual Functions-----------

 

 

#include<iostream> 

using namespace std; 

class B { 

public: 

         virtual void s()

}; 

class D: public B { 

public: 

      void s() { 

        cout<<"In Derived \n"; 

      } 

}; 

int main() { 

D d;

B *b= &d;  //pointer to base class B

b->s();

   return 0; 

} 

 

 

Constructors

 

 

#include <iostream>

using namespace std;

class student {

    int rno;

    char name[50];

    double fee;

public:

    student()

    {

        cout << "Enter the RollNo:";

        cin >> rno;

        cout << "Enter the Name:";

        cin >> name;

        cout << "Enter the Fee:";

        cin >> fee;

    }

 

    void display()

    {

        cout << endl << rno << "\t" << name << "\t" << fee;

    }

};

 

int main()

{

    s.display();

    return 0;

}

 

 

#include <iostream>

using namespace std;

 

class Test {

public:

    // User-Defined Constructor

    Test() { cout << "\n Constructor executed"; }

 

    // User-Defined Destructor

    ~Test() { cout << "\nDestructor executed"; }

};

main()

{

    Test t;

 

    return 0;

}

#include <iostream>

using namespace std;

 

class Rectangle {

private:

    int length, width;

 

public:

    // Parameterized Constructor

    Rectangle(int l, int w) {

        length = l;

        width = w;

    }

 

    // Function to calculate and display the area

    void calculateArea() {

        cout << "Area of Rectangle: " << (length * width) << endl;

    }

};

 

int main() {

    // Creating an object with parameters

    Rectangle rect(10, 5);

 

    // Calling the member function

    rect.calculateArea();

 

    return 0;

}

 

 

 

function overriding

 

#include <iostream>

using namespace std;

 

class A {

public:

    void Print()

    {

        cout << "Hi" << endl;

    }

};

 

class B : public A {

public:

    void Print()

    {

        cout << "My name is Astha Kathayat" << endl;

 

        A::Print(); // Calling the Print() function of the base class A

    }

};

 

int main()

{

    B obj;

    obj.Print();

    return 0;

}

 

 

 

Virtual Function

 

 

#include<iostream> 

using namespace std; 

class B { 

public: 

         virtual void s() { 

         cout<<" In Base \n"; 

      } 

}; 

class D: public B { 

public: 

      void s() { 

        cout<<"In Derived \n"; 

      } 

}; 

int main() { 

D d;

B *b= &d;  //pointer to base class B

b->s();

   return 0; 

} 

 

Copy Constructor

A copy constructor is a special constructor in object-oriented programming used to create a new object as a copy of an existing object. The main purpose of the copy constructor is to initialize an object with the data of another object of the same class.

#include <iostream>

using namespace std;

 

class Person {

private:

    string name;

    int age;

 

public:

    Person(string n, int a) {

        name = n;

        age = a;

    }

 

    Person(Person &p) {

        name = p.name;

        age = p.age;

        cout << "Copy constructor called!" << endl;

    }

 

    void display() {

        cout << "Name: " << name << ", Age: " << age << endl;

    }

 

 

};

 

int main() {

    Person person1("Alice", 25);

    Person person2 = person1; 

 

    person1.display();

    person2.display();

 

    return 0;

}

 

Encapsulation

Encapsulation in C++ is a fundamental concept in object-oriented programming (OOP) that involves bundling data (variables) and methods (functions) that operate on the data into a single unit, typically a class. It restricts direct access to some of the object's components, ensuring that the internal implementation details are hidden from the outside world and only the necessary interface is exposed.

 

Access Specifiers in C++

  • public: Members are accessible from outside the class.
  • private: Members are accessible only within the class.
  • protected: Members are accessible within the class and by derived classes.

 

Examples

 

#include <iostream>

using namespace std;

 

class Student {

private:

    string name;

    int age;

 

public:

    // Setter for name

    void setName(string studentName) {

        name = studentName;

    }

 

    // Getter for name

    string getName() {

        return name;

    }

 

    // Setter for age

    void setAge(int studentAge) {

        if (studentAge > 0) {

            age = studentAge;

        } else {

            cout << "Invalid age!" << endl;

        }

    }

 

    // Getter for age

    int getAge() {

        return age;

    }

};

 

int main() {

    Student s;

    s.setName("Alice");

    s.setAge(20);

 

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

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

 

    return 0;

}

#include <iostream>

using namespace std;

 

class Employee {

private:

    string name;

    int age;

    double salary;

 

public:

    // Setter for name

    void setName(string employeeName) {

        name = employeeName;

    }

 

    // Getter for name

    string getName() {

        return name;

    }

 

    // Setter for age

    void setAge(int employeeAge) {

        if (employeeAge > 0)

            age = employeeAge;

        else

            cout << "Invalid age! Please enter a positive number." << endl;

    }

 

    // Getter for age

    int getAge() {

        return age;

    }

 

    // Setter for salary

    void setSalary(double employeeSalary) {

        if (employeeSalary > 0)

            salary = employeeSalary;

        else

            cout << "Invalid salary! Please enter a positive value." << endl;

    }

 

    // Getter for salary

    double getSalary() {

        return salary;

    }

 

    // Method to display employee details

    void displayDetails() {

        cout << "\nEmployee Details:" << endl;

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

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

        cout << "Salary: $" << salary << endl;

    }

};

 

int main() {

    Employee emp;

 

    string name;

    int age;

    double salary;

 

    // Taking input from the user

    cout << "Enter employee name: ";

    getline(cin, name);

    emp.setName(name);

 

    cout << "Enter employee age: ";

    cin >> age;

    emp.setAge(age);

 

    cout << "Enter employee salary: ";

    cin >> salary;

    emp.setSalary(salary);

 

    // Display employee details

    emp.displayDetails();

 

    return 0;

}

 

 

 

 

 

 

 

 

 

 

This code demonstrates operator overloading in C++ for the ++ operator (prefix increment). Here's a detailed explanation of each part:


Class Definition

class Test 

{ 

   private: 

      int num; 

  • The Test class has a single private member variable num of type int.

Constructor

   public: 

       Test(int n) 

       {

           num = n;

       }

  • A parameterized constructor is defined to initialize num when an object of the class is created.
  • When an object is instantiated, the value passed as a parameter is assigned to num.

Overloading the ++ Operator

       void operator ++()        

       {  

           num = num + 2;  

       }

  • The ++ operator is overloaded using the operator keyword.
  • This implementation increments the value of num by 2 each time the ++ operator is applied.
  • This is a prefix increment operator, meaning the ++ is applied before any other operations on the object.

Print Method

       void Print()

       {  

           cout << "The Count is: " << num;  

       }

  • The Print method outputs the current value of num to the console.

main() Function

int main() 

{ 

    Test tt(8);     // Step 1: Create an object of class Test with num initialized to 8.

    ++tt;           // Step 2: Call the overloaded prefix '++' operator, adding 2 to num.

    tt.Print();     // Step 3: Call the Print method to display the updated value of num.

    return 0; 

}


Step-by-Step Execution

  1. Object Creation:
  2. Test tt(8);
    • The Test object tt is created, and the constructor initializes num to 8.
  3. Overloaded ++ Operator:
  4. ++tt;
    • The overloaded ++ operator is invoked.
    • Inside the overloaded method:
    • num = num + 2;
      • The value of num is updated from 8 to 10.
  5. Printing the Result:
  6. tt.Print();
    • The Print method is called, which displays:
    • The Count is: 10

Output

The Count is: 10


Key Concepts Demonstrated

  1. Operator Overloading:
    • The ++ operator is overloaded to perform a custom operation (adding 2 to num).
    • Overloaded operators provide a way to redefine the behavior of built-in operators for user-defined types.
  2. Prefix ++:
    • This implementation specifically handles the prefix increment operator. If the postfix (tt++) behavior is required, a separate implementation would be needed.
  3. Encapsulation:
    • The class encapsulates the data (num) and the operations on it (operator ++ and Print).

Improvement

If you want to handle postfix increment (tt++) as well, you can overload it separately. Here's how:

void operator ++(int)        

{  

    num = num + 1;  // Postfix increments by 1 (for demonstration purposes)

} 

Now, you can use both ++tt (prefix) and tt++ (postfix) in your program. Let me know if you'd like this fully implemented!

 

 

 

 

Comments

Popular posts from this blog

Basic DSA programs in c++

C++ Exception Handling and file handling