-1

Assuming I have a class MyClass(int i), I know I can do:

int j = 1;
MyClass instance(j);

i.e. declare and initialize instance in one line. Is there a short syntax that allows to do the same for a pointer to MyClass?

MyClass *instance = new MyClass(j);

works, but the syntax has "MyClass" two times, which is a bit redundant.

Daniel A. White
  • 181,601
  • 45
  • 354
  • 430
viron
  • 19
  • 4

2 Answers2

2
MyClass *instance = new MyClass(j);

works, but the syntax has "MyClass" two times, which is a bit redundant.

How about:

 auto instance = new MyClass(j);

But why will you want to allocate on the heap? See Object creation on the stack/heap? and Proper stack and heap usage in C++?

Community
  • 1
  • 1
WhiZTiM
  • 20,580
  • 3
  • 39
  • 60
  • Oh, busted, didn't think of `auto`. Well it doesn't include `MyClass` twice but I think OP was looking something shorted. Anyway, you deserve an upvote. – gsamaras Jun 19 '16 at 00:34
  • @gsamaras, :-) .. `auto` [AAA](https://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/) – WhiZTiM Jun 19 '16 at 00:42
0

No.

You should do it as you say.

gsamaras
  • 69,751
  • 39
  • 173
  • 279