Home > Software design >  Unable to create object from Main
Unable to create object from Main

Time:10-19

I'm new to C . This question might be easy, but I didn't find a proper answer to it after my Internet searches.

I have a class with a public method to do some task. From the main() method, I'm trying to instantiate an object of my class to further call my method. I'm getting a compile-time error:

MyClass: undeclared identifier

I checked undeclared identifier issues to be resolved by wrong spelling or missing namespaces, but didn't find any luck in my case.

I have a single .cpp file as below:

int main()
{
    MyClass sln; //Error here
    sln.MyMethod();
}
class MyClass {
public:
    void MyMethod() {
        //some code
    }
};

CodePudding user response:

You have to put the class definition before main() here, because it (the compiler) has to know the size of the object it is creating (instantiating).

//class definition
class MyClass {
public:
    void MyMethod() {
        //some code
    }
};

int main()
{
    MyClass sln;
    sln.MyMethod();
}

Check out the working program here.

  •  Tags:  
  • c
  • Related