At what condition is the default constructor gener

2020-04-08 09:26发布

I have the following class:

class Tileset { //base class

public:
    static std::vector<Tileset*> list;
    virtual ~Tileset() = 0;

protected:
    std::vector<Tile> tiles_list;
    sf::Texture sheet;

private: //non copiable
    Tileset(const Tileset&);
    Tileset& operator=(const Tileset&);
};

where sf::Texture has a default constructor

From my understanding a default constructor should be generated since every member can be default-constructed too. Yet I have a compiler error when I try to construct a derived object without calling a Tileset constructor. Can someone explain why no default constructor is generated?

edit : forgot to mention that Tile class doesn't have a default constructor. I'm not sure if that changes anything

3条回答
虎瘦雄心在
2楼-- · 2020-04-08 10:07

A default constructor will be not be generated if any of the following are true

  • There is a user defined constructor declared
  • The type has a const or reference field

You declared a constructor hence C++ won't provide a default generated one. In this case though all of the fields of Tileset have useful default constructors so defining a default constructor here is very easy

Tileset() { }
查看更多
Lonely孤独者°
3楼-- · 2020-04-08 10:08

From C++ spec, 12.1.5

If there is no user-declared constructor for class X, a default constructor is implicitly declared. An implicitly-declared default constructor is an inline public member of its class.

Your Tileset class declared a constructor, hence C++ compiler did not declare an implicit constructor for you. The rationale for this behavior is that since you provided constructors that take parameters, you probably need these parameters in order to properly initialize an instance of your class. The assumption here is that if you wanted a default constructor in addition to a non-default one, you'd simply declare it.

查看更多
来,给爷笑一个
4楼-- · 2020-04-08 10:16

When you don't provide any constructor, only then the compiler generates the default constructor for your class. If you provide a constructor (even copy-constructor), then compiler will not generate the default constructor.

By "provide" I mean when you declare and "optionally" define a constructor in your class.

查看更多
登录 后发表回答