Basic Cpp: OOP

OOP Content:

Fungsi utama dari OOP adalah untuk mengumpulkan data dan fungsi

1. Class dan Object

2. Data Abstraction

3. Encapsulation

4. Data Hiding

5. Inheritance

6. Polymorphism

Class dan Object

Class adalah blueprint/template/prototype yang mendifinisikan dan menjelaskan attribut dan dynamic behavios.

Class

class class_name 
{ 
private: 
  //data members and member functions declarations 
public: 
  //data members and member functions declarations 
protected: 
  //data members and member functions declarations 
};

Object

Instante/Object adalah realisasi dari class atau instant dari class atau object dari class

Declaring Object:

ClassName ObjectName;

Untuk mengakses data member dan member functions mengunakan operator dot (.), contoh: obj.printName()

Mengakses Data Members dan Member Function

The data members and member functions of class can be accessed using the dot(‘.’) operator with the object. For example if the name of object is obj and you want to access the member function with the name printName() then you will have to write obj.printName()

Mengakses Data Member

// C++ program to demonstrate 
// accessing of data members 

#include <bits/stdc++.h> 
using namespace std; 
class Geeks 
{ 
  // Access specifier 
  public: 

  // Data Members 
  string geekname; 

  // Member Functions() 
  void printname() 
  { 
  cout << "Geekname is: " << geekname; 
  } 
}; 

int main() { 

  // Declare an object of class geeks 
  Geeks obj1; 

  // accessing data member 
  obj1.geekname = "Abhi"; 

  // accessing member function 
  obj1.printname(); 
  return 0; 
} 

Output:

Geekname is: Abhi

Mengakses Member Functions:

Ada 2 cara mendeklarasikan member function:

1. Didalam class definition

2. Diluar class definition.

Untuk mendefine member function diluar class definition, gunakan scope resulation :: operator diantara nama class dan nama function

Contoh:

// C++ program to demonstrate function
// declaration outside class

#include <bits/stdc++.h>
using namespace std;
class Geeks
{
public:
string geekname;
int id;

// printname is not defined inside class defination
void printname();

// printid is defined inside class defination
void printid()
{
cout << "Geek id is: " << id;
}
};

// Definition of printname using scope resolution operator ::
void Geeks::printname()
{
cout << "Geekname is: " << geekname;
}
int main() {

Geeks obj1;
obj1.geekname = "xyz";
obj1.id=15;

// call printname()
obj1.printname();
cout << endl;

// call printid()
obj1.printid();
return 0;
}

Output:

Geekname is: xyz
Geek id is: 15

Constructors

Adalah special member class yang dipanggil oleh compiler setiap object dibuat. Constructor memiliki nama yang sama dengan nama class , bersifat public dan dapat didefine di dalam /diluar class

1. Default constructors

2. Parameter constructors

3. Copy constructors.

Contoh:

// C++ program to demonstrate constructors 

#include <bits/stdc++.h> 
using namespace std; 
class Geeks 
{ 
  public: 
  int id; 
  
  //Default Constructor 
  Geeks() 
  { 
    cout << "Default Constructor called" << endl; 
    id=-1; 
  } 
  
  //Parametrized Constructor 
  Geeks(int x) 
  { 
    cout << "Parametrized Constructor called" << endl; 
    id=x; 
  } 
}; 
int main() { 
  
  // obj1 will call Default Constructor 
  Geeks obj1; 
  cout << "Geek id is: " <<obj1.id << endl; 
  
  // obj1 will call Parametrized Constructor 
  Geeks obj2(21); 
  cout << "Geek id is: " <<obj2.id << endl; 
  return 0; 
} 

Output:

Default Constructor called
Geek id is: -1
Parametrized Constructor called
Geek id is: 21

Copy constructor berfungsi untuk membuat object baru, dengan cara mencopy.

class-name (class-name &){}

Destructors

Adalah special member function yang dipanggil compiler saat scope object berakhir

contoh:

// C++ program to explain destructors 

#include <bits/stdc++.h> 
using namespace std; 
class Geeks 
{ 
  public: 
  int id; 
  
  //Definition for Destructor 
  ~Geeks() 
  { 
    cout << "Destructor called for id: " << id <<endl; 
  } 
}; 

int main() 
{ 
  Geeks obj1; 
  obj1.id=7; 
  int i = 0; 
  while ( i < 5 ) 
  { 
    Geeks obj2; 
    obj2.id=i; 
    i++;		 
  } // Scope for obj2 ends here 

  return 0; 
} // Scope for obj1 ends here 

Output:

Destructor called for id: 0
Destructor called for id: 1
Destructor called for id: 2
Destructor called for id: 3
Destructor called for id: 4
Destructor called for id: 7

Data Abstraction

Data Abstraction

Data abstraction is one of the most essential and important feature of object oriented programming in C++. Abstraction means displaying only essential information and hiding the details. Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation.

Consider a real life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of car or applying brakes will stop the car but he does not know about how on pressing accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is.

Abstraction using Classes:
We can implement Abstraction in C++ using classes. Class helps us to group data members and member functions using available access specifiers. A Class can decide which data member will be visible to outside world and which is not.

Abstraction in Header files: One more type of abstraction in C++ can be header files. For example, consider the pow() method present in math.h header file. Whenever we need to calculate power of a number, we simply call the function pow() present in the math.h header file and pass the numbers as arguments without knowing the underlying algorithm according to which the function is actually calculating power of numbers.

Abstraction using access specifiers

Access specifiers are the main pillar of implementing abstraction in C++. We can use access specifiers to enforce restrictions on class members. For example:

  • Members declared as public in a class, can be accessed from anywhere in the program.
  • Members declared as private in a class, can be accessed only from within the class. They are not allowed to be accessed from any part of code outside the class.

We can easily implement abstraction using the above two features provided by access specifiers. Say, the members that defines the internal implementation can be marked as private in a class. And the important information needed to be given to the outside world can be marked as public. And these public members can access the private members as they are inside the class.

Example:

#include <iostream> 
using namespace std; 

class implementAbstraction 
{ 
  private: 
    int a, b; 

  public: 
  
    // method to set values of 
    // private members 
    void set(int x, int y) 
    { 
      a = x; 
      b = y; 
    } 
    
    void display() 
    { 
      cout<<"a = " <<a << endl; 
      cout<<"b = " << b << endl; 
    } 
}; 

int main() 
{ 
  implementAbstraction obj; 
  obj.set(10, 20); 
  obj.display(); 
  return 0; 
} 

Output:

a = 10
b = 20

You can see in the above program we are not allowed to access the variables a and b directly, however one can call the function set() to set the values in a and b and the function display() to display the values of a and b.

Advantages of Data Abstraction:

  • Helps the user to avoid writing the low level code
  • Avoids code duplication and increases reusability.
  • Can change internal implementation of class independently without affecting the user.
  • Helps to increase security of an application or program as only important details are provided to the user.

Encapsulation

Fungsi encapsulation adalah membungkus data dan function menjadi satu unit dan data tersebut tidak dapat diakses dari luar, hanya function yang berhubungan dengan dunia luar

// c++ program to explain 
// Encapsulation 

#include<iostream> 
using namespace std; 

class Encapsulation 
{ 
  private: 
    // data hidden from outside world 
    int x; 
    
  public: 
    // function to set value of 
    // variable x 
    void set(int a) 
    { 
      x =a; 
    } 
    
    // function to return value of 
    // variable x 
    int get() 
    { 
      return x; 
    } 
}; 

// main function 
int main() 
{ 
  Encapsulation obj; 
  
  obj.set(5); 
  
  cout<<obj.get(); 
  return 0; 
} 

output:

5

In the above program the variable x is made private. This variable can be accessed and manipulated only using the functions get() and set() which are present inside the class. Thus we can say that here, the variable x and the functions get() and set() are binded together which is nothing but encapsulation.

Role of access specifiers in encapsulation

As we have seen in above example, access specifiers plays an important role in implementing encapsulation in C++. The process of implementing encapsulation can be sub-divided into two steps:

  1. The data members should be labeled as private using the private access specifiers
  2. The member function which manipulates the data members should be labeled as public using the public access specifier

Data Hiding

Access modifiers/Access Specifier  dikenal dengan Data Hiding yang berfungsi untuk mengset accesability dari member class.

1. Public

2. Private

3. Protected

Public

Data member dan member functions dapat diaccess dari luar class

// C++ program to demonstrate public 
// access modifier 

#include<iostream> 
using namespace std; 

// class definition 
class Circle 
{ 
  public: 
    double radius; 
    
    double compute_area() 
    { 
      return 3.14*radius*radius; 
    } 
  
}; 

// main function 
int main() 
{ 
  Circle obj; 
  
  // accessing public datamember outside class 
  obj.radius = 5.5; 
  
  cout << "Radius is:" << obj.radius << "\n"; 
  cout << "Area is:" << obj.compute_area(); 
  return 0; 
} 

Output:

Radius is:5.5
Area is:94.985

In the above program the data member radius is public so we are allowed to access it outside the class.

Private

Data member dan member functions tidak dapat diaccess dari lua, hanya dapat diaccess oleh function di dalam class dan friend function

// C++ program to demonstrate private 
// access modifier 

#include<iostream> 
using namespace std; 

class Circle 
{ 
  // private data member 
  private: 
    double radius; 
  
  // public member function	 
  public:	 
    double compute_area() 
    { // member function can access private 
      // data member radius 
      return 3.14*radius*radius; 
    } 
  
}; 

// main function 
int main() 
{ 
  // creating object of the class 
  Circle obj; 
  
  // trying to access private data member 
  // directly outside the class 
  obj.radius = 1.5; 
  
  cout << "Area is:" << obj.compute_area(); 
  return 0; 
} 

The output of above program will be a compile time error because we are not allowed to access the private data members of a class directly outside the class.
Output:

 In function 'int main()':
11:16: error: 'double Circle::radius' is private
         double radius;
                ^
31:9: error: within this context
     obj.radius = 1.5;
         ^

However we can access the private data members of a class indirectly using the public member functions of the class. Below program explains how to do this:

// C++ program to demonstrate private 
// access modifier 

#include<iostream> 
using namespace std; 

class Circle 
{ 
  // private data member 
  private: 
    double radius; 
  
  // public member function	 
  public:	 
    double compute_area(double r) 
    { // member function can access private 
      // data member radius 
      radius = r; 
      
      double area = 3.14*radius*radius; 
      
      cout << "Radius is:" << radius << endl; 
      cout << "Area is: " << area; 
    } 
  
}; 

// main function 
int main() 
{ 
  // creating object of the class 
  Circle obj; 
  
  // trying to access private data member 
  // directly outside the class 
  obj.compute_area(1.5); 
  
  
  return 0; 
} 

Output:

Radius is:1.5
Area is: 7.065

Protected

Protected access modifier is similar to that of private access modifiers, the difference is that the class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.

// C++ program to demonstrate 
// protected access modifier 
#include <bits/stdc++.h> 
using namespace std; 

// base class 
class Parent 
{ 
  // protected data members 
  protected: 
  int id_protected; 
  
}; 

// sub class or derived class 
class Child : public Parent 
{ 
  
  
  public: 
  void setId(int id) 
  { 
    
    // Child class is able to access the inherited 
    // protected data members of base class 
    
    id_protected = id; 
    
  } 
  
  void displayId() 
  { 
    cout << "id_protected is:" << id_protected << endl; 
  } 
}; 

// main function 
int main() { 
  
  Child obj1; 
  
  // member function of derived class can 
  // access the protected data members of base class 
  
  obj1.setId(81); 
  obj1.displayId(); 
  return 0; 
} 

Output:

id_protected is:81

Inheritance/Pewarisan

Inheritance adalah kemampuan salah satu class (derived class) untuk mewarisi properti dan method lain dari class (Base class/Super Class)

Why and when to use inheritance?

Consider a group of vehicles. You need to create classes for Bus, Car and Truck. The methods fuelAmount(), capacity(), applyBrakes() will be same for all of the three classes. If we create these classes avoiding inheritance then we have to write all of these functions in each of the three classes as shown in below figure:

You can clearly see that above process results in duplication of same code 3 times. This increases the chances of error and data redundancy. To avoid this type of situation, inheritance is used. If we create a class Vehicle and write these three functions in it and inherit the rest of the classes from the vehicle class, then we can simply avoid the duplication of data and increase re-usability. Look at the below diagram in which the three classes are inherited from vehicle class:

Using inheritance, we have to write the functions only one time instead of three times as we have inherited rest of the three classes from base class(Vehicle).

For creating a sub-class which is inherited from the base class we have to follow the below syntax.

class subclass_name : access_mode base_class_name
{
  //body of subclass
};
// C++ program to demonstrate implementation 
// of Inheritance 

#include <bits/stdc++.h> 
using namespace std; 

//Base class 
class Parent 
{ 
  public: 
  int id_p; 
}; 

// Sub class inheriting from Base Class(Parent) 
class Child : public Parent 
{ 
  public: 
  int id_c; 
}; 

//main function 
int main() 
{ 
  
    Child obj1; 
    
    // An object of class child has all data members 
    // and member functions of class parent 
    obj1.id_c = 7; 
    obj1.id_p = 91; 
    cout << "Child id is " << obj1.id_c << endl; 
    cout << "Parent id is " << obj1.id_p << endl; 
    
    return 0; 
} 

Output:

Child id is 7
Parent id is 91

In the above program the ‘Child’ class is publicly inherited from the ‘Parent’ class so the public data members of the class ‘Parent’ will also be inherited by the class ‘Child’.

Modes of Inheritance

  1. Public mode: If we derive a sub class from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in derived class.
  2. Protected mode: If we derive a sub class from a Protected base class. Then both public member and protected members of the base class will become protected in derived class.
  3. Private mode: If we derive a sub class from a Private base class. Then both public member and protected members of the base class will become Private in derived class.

Note : The private members in the base class cannot be directly accessed in the derived class, while protected members can be directly accessed. For example, Classes B, C and D all contain the variables x, y and z in below example. It is just question of access.

// C++ Implementation to show that a derived class 
// doesn’t inherit access to private data members. 
// However, it does inherit a full parent object 
class A 
{ 
public: 
  int x; 
protected: 
  int y; 
private: 
  int z; 
}; 

class B : public A 
{ 
  // x is public 
  // y is protected 
  // z is not accessible from B 
}; 

class C : protected A 
{ 
  // x is protected 
  // y is protected 
  // z is not accessible from C 
}; 

class D : private A // 'private' is default for classes 
{ 
  // x is private 
  // y is private 
  // z is not accessible from D 
}; 

he below table summarizes the above three modes and shows the access specifier of the members of base class in the sub class when derived in public, protected and private modes:

Types of Inheritance in C++

Single Inheritance: In single inheritance, a class is allowed to inherit from only one class. i.e. one sub class is inherited by one base class only.

Syntax:

class subclass_name : access_mode base_class
{
  //body of subclass
};
// C++ program to explain 
// Single inheritance 
#include <iostream> 
using namespace std; 

// base class 
class Vehicle { 
public: 
  Vehicle() 
  { 
  cout << "This is a Vehicle" << endl; 
  } 
}; 

// sub class derived from two base classes 
class Car: public Vehicle{ 

}; 

// main function 
int main() 
{ 
  // creating object of sub class will 
  // invoke the constructor of base classes 
  Car obj; 
  return 0; 
} 

Output:

This is a vehicle

Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. i.e one sub class is inherited from more than one base classes.
Syntax:

class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
  //body of subclass
};

Here, the number of base classes will be separated by a comma (‘, ‘) and access mode for every base class must be specified.

// C++ program to explain 
// multiple inheritance 
#include <iostream> 
using namespace std; 

// first base class 
class Vehicle { 
public: 
  Vehicle() 
  { 
  cout << "This is a Vehicle" << endl; 
  } 
}; 

// second base class 
class FourWheeler { 
public: 
  FourWheeler() 
  { 
  cout << "This is a 4 wheeler Vehicle" << endl; 
  } 
}; 

// sub class derived from two base classes 
class Car: public Vehicle, public FourWheeler { 

}; 

// main function 
int main() 
{ 
  // creating object of sub class will 
  // invoke the constructor of base classes 
  Car obj; 
  return 0; 
} 

Output:

This is a Vehicle
This is a 4 wheeler Vehicle

Multilevel Inheritance: In this type of inheritance, a derived class is created from another derived class.

 

// C++ program to implement 
// Multilevel Inheritance 
#include <iostream> 
using namespace std; 

// base class 
class Vehicle 
{ 
public: 
  Vehicle() 
  { 
  cout << "This is a Vehicle" << endl; 
  } 
}; 
class fourWheeler: public Vehicle 
{ public: 
  fourWheeler() 
  { 
  cout<<"Objects with 4 wheels are vehicles"<<endl; 
  } 
}; 
// sub class derived from two base classes 
class Car: public fourWheeler{ 
public: 
  car() 
  { 
  cout<<"Car has 4 Wheels"<<endl; 
  } 
}; 

// main function 
int main() 
{ 
  //creating object of sub class will 
  //invoke the constructor of base classes 
  Car obj; 
  return 0; 
} 

output:

This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels

Hierarchical Inheritance: In this type of inheritance, more than one sub class is inherited from a single base class. i.e. more than one derived class is created from a single base class.

// C++ program to implement 
// Hierarchical Inheritance 
#include <iostream> 
using namespace std; 

// base class 
class Vehicle 
{ 
public: 
  Vehicle() 
  { 
  cout << "This is a Vehicle" << endl; 
  } 
}; 


// first sub class 
class Car: public Vehicle 
{ 

}; 

// second sub class 
class Bus: public Vehicle 
{ 
  
}; 

// main function 
int main() 
{ 
  // creating object of sub class will 
  // invoke the constructor of base class 
  Car obj1; 
  Bus obj2; 
  return 0; 
} 

Output:

This is a Vehicle
This is a Vehicle

Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance.
Below image shows the combination of hierarchical and multiple inheritance:

// C++ program for Hybrid Inheritance 

#include <iostream> 
using namespace std; 

// base class 
class Vehicle 
{ 
public: 
  Vehicle() 
  { 
  cout << "This is a Vehicle" << endl; 
  } 
}; 

//base class 
class Fare 
{ 
  public: 
  Fare() 
  { 
    cout<<"Fare of Vehicle\n"; 
  } 
}; 

// first sub class 
class Car: public Vehicle 
{ 

}; 

// second sub class 
class Bus: public Vehicle, public Fare 
{ 
  
}; 

// main function 
int main() 
{ 
  // creating object of sub class will 
  // invoke the constructor of base class 
  Bus obj2; 
  return 0; 
} 

Output:

This is a Vehicle
Fare of Vehicle

Polymorphism

Polimorphism adalah kemampuan data untuk diprosess lebih dari satu bentuk.

In C++ polymorphism is mainly divided into two types:

Compile time Polymorphism

Runtime Polymorphism

Compile time polymorphism: This type of polymorphism is achieved by function overloading or operator overloading.

Function Overloading: When there are multiple functions with same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by change in number of arguments or/and change in type of arguments.

// C++ program for function overloading 
#include <bits/stdc++.h> 

using namespace std; 
class Geeks 
{ 
  public: 
  
  // function with 1 int parameter 
  void func(int x) 
  { 
    cout << "value of x is " << x << endl; 
  } 
  
  // function with same name but 1 double parameter 
  void func(double x) 
  { 
    cout << "value of x is " << x << endl; 
  } 
  
  // function with same name and 2 int parameters 
  void func(int x, int y) 
  { 
    cout << "value of x and y is " << x << ", " << y << endl; 
  } 
}; 

int main() { 
  
  Geeks obj1; 
  
  // Which function is called will depend on the parameters passed 
  // The first 'func' is called 
  obj1.func(7); 
  
  // The second 'func' is called 
  obj1.func(9.132); 
  
  // The third 'func' is called 
  obj1.func(85,64); 
  return 0; 
} 

 

Output:

value of x is 7
value of x is 9.132
value of x and y is 85, 64

In the above example, a single function named func acts differently in three different situations which is the property of polymorphism.

Operator Overloading: C++ also provide option to overload operators. For example, we can make the operator (‘+’) for string class to concatenate two strings. We know that this is the addition operator whose task is to add to operands. So a single operator ‘+’ when placed between integer operands , adds them and when placed between string operands, concatenates them.
Example:

// CPP program to illustrate 
// Operator Overloading 
#include<iostream> 
using namespace std; 

class Complex { 
private: 
  int real, imag; 
public: 
  Complex(int r = 0, int i =0) {real = r; imag = i;} 
  
  // This is automatically called when '+' is used with 
  // between two Complex objects 
  Complex operator + (Complex const &obj) { 
    Complex res; 
    res.real = real + obj.real; 
    res.imag = imag + obj.imag; 
    return res; 
  } 
  void print() { cout << real << " + i" << imag << endl; } 
}; 

int main() 
{ 
  Complex c1(10, 5), c2(2, 4); 
  Complex c3 = c1 + c2; // An example call to "operator+" 
  c3.print(); 
} 

Output:

12 + i9

In the above example the operator ‘+’ is overloaded. The operator ‘+’ is an addition operator and can add two numbers(integers or floating point) but here the operator is made to perform addition of two imaginary or complex numbers. To learn operator overloading in details visit this link.

Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.

Function overriding on the other hand occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.

// C++ program for function overriding 

#include <bits/stdc++.h> 
using namespace std; 

class base 
{ 
public: 
  virtual void print () 
  { cout<< "print base class" <<endl; } 

  void show () 
  { cout<< "show base class" <<endl; } 
}; 

class derived:public base 
{ 
public: 
  void print () //print () is already virtual function in derived class, we could also declared as virtual void print () explicitly 
  { cout<< "print derived class" <<endl; } 

  void show () 
  { cout<< "show derived class" <<endl; } 
}; 

//main function 
int main() 
{ 
  base *bptr; 
  derived d; 
  bptr = &d; 
  
  //virtual function, binded at runtime (Runtime polymorphism) 
  bptr->print(); 
  
  // Non-virtual function, binded at compile time 
  bptr->show(); 

  return 0; 
} 

Output:

print derived class
show base class

To learn runtime polymorphism in details visit this link.

 

Some important points to know about OOP:

  1. OOP treats data as a critical element.
  2. Emphasis is on data rather than procedure.
  3. Decomposition of the problem into simpler modules.
  4. Doesn’t allow data to freely flow in the entire system, ie localized control flow.
  5. Data is protected from external functions.

Advantages of OOPs –

  • It models the real world very well.
  • With OOP, programs are easy to understand and maintain.
  • OOP offers code reusability. Already created classes can be reused without having to write them again.
  • OOP facilitates the quick development of programs where parallel development of classes is possible.
  • With OOP, programs are easier to test, manage and debug.

Disadvantages of OOP –

  • With OOP, classes sometimes tend be over-generalised.
  • The relations among classes become superficial at times.
  • The OOP design is tricky and requires appropriate knowledge. Also, one needs to do proper planning and design for OOP programming.
  • To program with OOP, the programmer needs proper skills such as that of design, programming and thinking in terms of objects and classes etc.

Passing Object ke function

Contoh:

#include <iostream>
using namespace std;

class Complex
{
    private:
       int real;
       int imag;
    public:
       Complex(): real(0), imag(0) { }
       void readData()
        {
           cout << "Enter real and imaginary number respectively:"<<endl;
           cin >> real >> imag;
        }
        void addComplexNumbers(Complex comp1, Complex comp2)
        {
           // real represents the real data of object c3 because this function is called using code c3.add(c1,c2);
            real=comp1.real+comp2.real;

             // imag represents the imag data of object c3 because this function is called using code c3.add(c1,c2);
            imag=comp1.imag+comp2.imag;
        }

        void displaySum()
        {
            cout << "Sum = " << real<< "+" << imag << "i";
        }
};
int main()
{
    Complex c1,c2,c3;

    c1.readData();
    c2.readData();

    c3.addComplexNumbers(c1, c2);
    c3.displaySum();

    return 0;
}

Output

Enter real and imaginary number respectively:
2
4
Enter real and imaginary number respectively:
-3
4
Sum = -1+8i

Return Object dari Function

#include <iostream>
using namespace std;
class Complex
{
    private:
       int real;
       int imag;
    public:
       Complex(): real(0), imag(0) { }
       void readData()
        {
           cout << "Enter real and imaginary number respectively:"<<endl;
           cin >> real >> imag;
        }
        Complex addComplexNumbers(Complex comp2)
        {
            Complex temp;

            // real represents the real data of object c3 because this function is called using code c3.add(c1,c2);
            temp.real = real+comp2.real;

            // imag represents the imag data of object c3 because this function is called using code c3.add(c1,c2);
            temp.imag = imag+comp2.imag;
            return temp;
        }
        void displayData()
        {
            cout << "Sum = " << real << "+" << imag << "i";
        }
};

int main()
{
    Complex c1, c2, c3;

    c1.readData();
    c2.readData();

    c3 = c1.addComplexNumbers(c2);

    c3.displayData();
    
    return 0;
}

 

 

 

 

 

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *