简体   繁体   English

仅在C ++中声明默认构造函数

[英]Only declaring a default constructor in C++

I wish to know if i only declare (and not define) a default constructor in a derived class, why doesn't the base class constructor gets invoked when i create an object of derived class? 我想知道我是否只在派生类中声明(而不是定义)默认构造函数,为什么在创建派生类的对象时不会调用基类构造函数?

Also is it a common practice to only declare default constructors? 通常的做法是只声明默认构造函数吗? If yes, what are advantages of the same? 如果是的话,同样的优点是什么?

class A
{
  private:
  A() {}
}

class B : public A
{
  B();
}

doesn't give compilation errors, but 不会给出编译错误,但是

class B : public A
{ 
  B() {}
}

gives the error :- In constructor B::B(): error: A::A() is private. 给出错误: - 在构造函数B :: B()中:错误:A :: A()是私有的。

What is the justification for the same? 同样的理由是什么?

class B : public A
{
  B();
}

In this case, compiler accepts that because you could implement B() using any public or protected constructor for A. It is not implementation, so at this point you are not using A(). 在这种情况下,编译器接受这一点,因为您可以使用任何公共或受保护的构造函数为A实现B()。它不是实现,因此此时您不使用A()。

class B : public A
{
  B(){};
}

Here you're implicitly using empty A constructor, that is declared private, so is illegal. 在这里你隐式使用空A构造函数,它被声明为私有,因此是非法的。

Declaring all constructor private disallows derivation. 声明所有构造函数私有不允许派生。 I suppose it's useful for someone in some circunstances 我想这对某些环境中的某些人有用

Can you provide an example? 你能提供一个例子吗? It seems strange that the code compile and runs if you really declare but not define the constructor. 如果你真的声明但没有定义构造函数,代码编译并运行似乎很奇怪。 You should have an undefined reference to the derived constructor. 您应该对派生的构造函数有一个未定义的引用。

Usually you would only declare-and-not-define a member function that you want to prevent being used. 通常,您只会声明并且不定义要阻止使用的成员函数。 For example, you can declare-and-not-define a copy constructor (privately) to prevent the object from being copied. 例如,您可以声明并且不定义复制构造函数(私有)以防止复制对象。 The "prevention" here is actually achieved through an undefined reference compilation error. 这里的“预防”实际上是通过未定义的引用编译错误实现的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM