Object assignment : instance object « Class « C++ Tutorial






#include <iostream> 
using namespace std; 
 
class MyClass { 
  int a, b; 
public: 
  void setAB(int i, int j) { a = i, b = j; } 
  void display() { 
    cout << "\n a is " << a << '\n'; 
    cout << "\n b is " << b << '\n'; 
  } 
}; 
 
int main() 
{ 
  MyClass ob1, ob2; 
 
  ob1.setAB(10, 20); 
  ob2.setAB(0, 0); 
  cout << "ob1 before assignment:"; 
  ob1.display(); 
  cout << "ob2 before assignment:"; 
  ob2.display(); 
 
  ob2 = ob1; // assign ob1 to ob2 
 
  cout << "ob1 after assignment:"; 
  ob1.display(); 
  cout << "ob2 after assignment:"; 
  ob2.display(); 
 
  ob1.setAB(-1, -1); // change ob1 
 
  cout << "ob1 after changing ob1:"; 
  ob1.display(); 
  cout << "ob2 after changing ob1:"; 
  ob2.display(); 
 
  return 0; 
}
ob1 before assignment:
 a is 10

 b is 20
ob2 before assignment:
 a is 0

 b is 0
ob1 after assignment:
 a is 10

 b is 20
ob2 after assignment:
 a is 10

 b is 20
ob1 after changing ob1:
 a is -1

 b is -1
ob2 after changing ob1:
 a is 10

 b is 20








9.32.instance object
9.32.1.Using an empty initializer
9.32.2.Automatically converted into MyClass(4): MyClass ob = 4;
9.32.3.MyClass ob(4)
9.32.4.MyClass ob = MyClass(4);
9.32.5.Creates two objects.
9.32.6.Object assignment
9.32.7.Creating objects on the heap using new
9.32.8.Accessing members of objects on the heap
9.32.9.Call class constructor without new operator
9.32.10.Assign class object