Heisenberg
Heisenberg

Reputation: 78

Object Instantiation in c ++ with a protected constructor

I have this c++ class and I want to initialize an object of this type:

class MyClass

{
public:

   /**
     *  Creates an instance of this class.
     *  @return Pointer to the created object.
     */    
static MyClass * Create ();


protected:
    // Explicit protected Constructor 
    //and Copy-Constructor, use Create() to create an  instance of this object.
    MyClass();

}

To create an instance, I did this:

static MyClass * m_object = myClass.Create();

but I got those warnings and errors:

   warning C4832: token '.' is illegal after UDT 'MyClass'

   error C2275: 'MyClass' : illegal use of this type as an expression

   error C2228: left of '.Create' must have class/struct/union

How to instantiate properly this object?

Upvotes: 0

Views: 194

Answers (2)

if-else-switch
if-else-switch

Reputation: 977

To call static member you have to use class name instead of object name. Your object instantiation should be like this.

MyClass *m_object = MyClass::Create();

Upvotes: 1

Elixir Techne
Elixir Techne

Reputation: 1856

In C++, Static variables/methods are access using scope resolution (::) operator.

change your code to

static MyClass * m_object = MyClass::Create();

Upvotes: 4

Related Questions