2

in c++, whats the difference between writing something like

myclass myobject();
//and
myclass myobject;

also i'm new to stack overflow so if i'm doing something wrong just tell me.

  • 1
    Closely related: http://stackoverflow.com/questions/620137/do-the-parentheses-after-the-type-name-make-a-difference-with-new – abelenky Apr 11 '17 at 03:15
  • 1
    This is related too: https://stackoverflow.com/questions/1613341/what-do-the-following-phrases-mean-in-c-zero-default-and-value-initializat – Retired Ninja Apr 11 '17 at 03:17
  • 1
    Possible duplicate of [Default constructor with empty brackets](http://stackoverflow.com/questions/180172/default-constructor-with-empty-brackets) – Trevor Merrifield Apr 11 '17 at 03:17
  • 1
    and, though off topic: change your habit to use `{}` instead of `()` for object construction. In your case, `myclass myobject{};` is a valid way to construct an object instead of mistakenly declaring a function – Adrian Shum Apr 11 '17 at 03:57

2 Answers2

3

When you write:

myclass myobject(); 

You may think you're creating a new object of type myclass, but you actually declared a function called myobject, that takes no parameters, and has a return-type of myclass.

If you want to see that for sure, check this code:

#include <stdio.h>
#include <iostream>

using namespace std;

class myclass 
{ public: int ReturnFive() { return 5; } };

int main(void) {
    myclass myObjectA;
    myclass myObjectB();                    // Does NOT declare an object
    cout << myObjectA.ReturnFive() << endl; // Uses ObjectA
    cout << myObjectB.ReturnFive() << endl; // Causes a compiler error!
    return 0;
}


prog.cpp: In function ‘int main()’:
prog.cpp:18:23: error: request for member ‘ReturnFive’ in ‘myObjectB’, which is of non-class type ‘myclass()’
     cout << myObjectB.ReturnFive() << endl;
                       ^~~~~~~~~~
abelenky
  • 63,815
  • 23
  • 109
  • 159
2

The difference is same as,

int a; and int a();

I am pretty sure that you understand now. Just for the sake of answer, I am explaining it below.

int a; // -> a is a variable of type int
int a(); // -> a is a function returning int with void paramters
Abhineet
  • 5,320
  • 1
  • 25
  • 43