Creating objects on the heap using new : instance object « Class « C++ Tutorial






#include <iostream>

class MyClass
{
public:
    MyClass();
    ~MyClass();
private:
    int itsAge;
};

MyClass::MyClass()
{
    std::cout << "Constructor called.\n";
    itsAge = 1;
}

MyClass::~MyClass()
{
    std::cout << "Destructor called.\n";
}

int main()
{
    std::cout << "MyClass ...\n";
    MyClass Frisky;

    std::cout << "MyClass *pRags = new MyClass...\n";
    MyClass * pRags = new MyClass;

    std::cout << "delete pRags...\n";
    delete pRags;

    std::cout << "Exiting, watch go...\n";
    return 0;
}
MyClass ...
Constructor called.
MyClass *pRags = new MyClass...
Constructor called.
delete pRags...
Destructor called.
Exiting, watch go...
Destructor called.








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