class Base1 {

//Not a polymorphic type.

//additional class details omitted

};

 

class Base2 {

 

virtual void f();

// Make Base2 polymorphic.

//additional class details

//omitted

};

void Base2::f()

{

// Define Base2 function.

}

class Derived : public virtual Base1, public virtual Base2 { // additional class details omitted

};

int main()

{

Base1 *bp1; Base2 *bp2; Derived *dp;

bp1 = new Derived; bp2 = new Derived;

// dp = (Derived *) bp1;

//Problem: compile time error

//Can’t cast from virtual base.

// dp = (Derived *) bp2;

//Problem: compile time error

//Can’t cast from virtual base.

//dp = dynamic_cast<Derived *> bp1;

//Problem: compile time error

//Can’t cast from

//non-polymorphic type.

dp = dynamic_cast<Derived *> bp2;

// OK

}

 

explicit Keyword

explicit Keyword

The explicit keyword is used for declaring constructor functions within class declarations. When these functions are declared explicit, they cannot be used for implicit conversions.

Usage

While constructors taking one argument are often useful in the design of a class, they can allow inadvertent conversion in expressions. This can introduce subtle bugs. The explicit keyword allows a class designer to prohibit such implicit conversions. It is often used in the production of class libraries.

Example

class C { public:

HP aC++ Keywords 141