Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: C++
Expertise: Beginner
May 2, 2000



Application Security Testing: An Integral Part of DevOps

Constructors - Derived to Base

My base class contains this constructor:

class Parent {
  Parent(int a, int b, char* c);

My derived class contains this constructor:

class Child : public Parent {
  Child(int a);

defined as

Child::Child(int a) : Parent(a,2)
  .. some code

I need a third class derived from class Child class Grandchild :

public Child {
  Grandchild(int a);

but I can't figure out how to define the constructor. I've tried:

Grandchild::Grandchild(int a):Child (a,2)

Grandchild::Grandchild(int a):Parent(a,2)

Grandchild::Grandchild(int a):Child(a):Parent(2)

Grandchild::Grandchild(int a):Child(a),Parent(2)

You can't initialize a non-immediate base class in a derived class (virtual base classes are an exception to this rule). What you need is to have class GrandChild initialize Child, and delegate the responsibility of initializing Parent to Child's constructor:

class Grandchild : public Child 
 Grandchild(int a):Child (a,2){}//implicit init of Parent

Child's constructor automatically initializes Parent with the values a and 2.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date