0

I am new to c++. I can manage the first one. we are allocating the memory in heap. I can't understand the second case.

Myclass * classobj =new Myclass;

Myclass * classobj = new Myclass();

here is an example I am testing with ubuntu

#include<iostream>
#include <stdio.h>
using namespace std;

class myclass{
public:
int i;
int j;
myclass();
};

myclass::myclass()
{
i=5;
j=7;
}

int main()
{
myclass *classobj= new myclass;

printf("%d %d",classobj->i,classobj->j);
}

when I run the above program it is printing 5 and 7 for both "new myclass" and "new myclass()". please tell me what is the difference

Bts Rts
  • 1
  • 2
  • calls constructor `MyClass()` and allocated on the heap. – Bill May 26 '13 at 13:21
  • Maybe you already understand this, but avoid `new` and prefer plain `Myclass classobj;` when possible. – aschepler May 26 '13 at 13:23
  • 3
    @aschepler they're 2 wholly different use cases, why recommend one over the other? It depends entirely on the intended lifecycle and usage which approach to avoid, and which to prefer. – Niels Keurentjes May 26 '13 at 13:26
  • I have added an example. Pls tell the difference with and without calling constructor – Bts Rts May 26 '13 at 14:09

0 Answers0