Home > database >  How do I instantiate a class without an implicit/explicit constructor?
How do I instantiate a class without an implicit/explicit constructor?

Time:11-02

Can someone help understanding this code?

I have Foo class which does not have constructor and all of its methods are virtual.
I only got headers.

class Bar;
class USER_API IFoo
{
public:

    virtual ~IFoo() {}

    virtual uint32_t GetWidth() const = 0;
    // more virtual methods...
};

class USER_API Foo
    : public IFoo
{
public:
    virtual Bar *GetBar() = 0;
};

It has no constructor, so I can not use auto ptrFoo = new Foo method.
Is this mean Foo class does not have implicit/explicit constructor?

If yes, how can I prevent calling of default constructor?
The only way I know of is to make the constructor a protected member. But in this header no declaration of c'tor.

I can get pointer of Foo instance from GetFoo() method in Bar class below.

class Foo;
class USER_API Bar
{
public:
    Bar();
    virtual ~Bar();

    Foo *GetFoo();
    const Foo *GetFoo() const;
}

I am curious about, How Bar.cpp create and have instance of Foo?
What I'm guessing is that Bar.cpp has a class that inherits from class Foo.

Any hint would be appreciated..

CodePudding user response:

Foo does have an implicit constructor, because it is neither explicitly defined nor explicitly deleted.

You can make the implicit (default) constructor protected by just writing that.

 protected:
    Foo() = default;

CodePudding user response:

In general, if you don't want a class to be instantiated you need to make private its constructor. Therefore nobody will be able to call it and therefore make instance of it. For create an instance you would need then to define a static member function that invoke the private constructor (since member functions of a class have access to private members).

The other option is the class to be abstract, as your class IFoo. An abstract class cannot be instantiated although sometimes is remarked declaring the constructor protected:

class Base_class {
  public:
    virtual ~Base_class() = 0;
  protected:
    Base_class() {}
};

In your case, Foo is not abstract and its Constructor is not declared, so it has a default constructor and it can be instantiated. If you don't have access to Foo you can not modify this behavior

  • Related