0

I was learning constructors when i encountered a error which i couldn't understood.

vector<int> myvector();
cout << myvector.size();

I was dealing with my own class first, and was getting Expression must have a class type. So i tried with C++ STL and was getting the same error.

What's more none of my constructors were printing anything when i did like this, so it understood its not calling, but there was no compilation error, if i just write vector<int> myvector();

My Sample code for the class i declared

class MyClass
{
public:
    MyClass()
    {
        cout << "No paramter passed";
    }
    MyClass(string str)
    {
        cout << "String passed\n";
    }
};


int main()
{
    MyClass myobj();

    return 0;
}

In this none of the constructors were called, neither compilation error.

  • 3
    you're declaring a function not creating an object, just use `MyClass myobj;` – Alan Birtles Oct 28 '20 at 08:12
  • 1
    Turn on your warnings: warning: empty parentheses interpreted as a function declaration. note: remove parentheses to declare a variable – RvdK Oct 28 '20 at 08:16
  • Thank you for answer, I understood what i did, just a curious question, can we do any operation using this type of declaration of function, or its just a function declaration with no use. @AlanBirtles – DEV Awasthi Oct 28 '20 at 08:16
  • 1
    its the same as any other declaration, you can call it but you'll get an undefined symbol if there isn't a definition available somewhere – Alan Birtles Oct 28 '20 at 08:21

0 Answers0