Accessing members of objects on the heap : instance object « Class « C++ Tutorial






#include <iostream>
 
 class MyClass
 {
 public:
     MyClass() {
         itsAge = 2; 
     }
     ~MyClass() {}
     int GetAge() const { 
         return itsAge; 
     }
     void SetAge(int age) { 
         itsAge = age; 
     }
 private:
     int itsAge;
 };
 
 int main()
 {
     MyClass * myObject = new MyClass;
     std::cout << "myObject is " << myObject->GetAge() << " years old\n";
 
     myObject->SetAge(5);
     std::cout << "myObject is " << myObject->GetAge() << " years old\n";
 
     delete myObject;
     return 0;
 }
myObject is 2 years old
myObject is 5 years old








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