Govt. Exams
Entrance Exams
An abstract class with at least one pure virtual function cannot be instantiated directly. However, it serves as a blueprint for derived classes and can have constructors, destructors, and other functions.
class Test { public: static int count; };
int Test::count = 0;
int main() { Test t1, t2; Test::count = 5; cout
Static members are shared by all instances of a class. When Test::count is set to 5, this value is shared across all objects t1 and t2, so both print 5.
The Diamond Problem occurs when a derived class inherits from two classes that both inherit from a common base class, creating multiple inheritance paths and ambiguity about which base class members to use. Virtual inheritance solves this.
Shallow copy performs a bitwise copy of members, which can be problematic for pointers (both objects point to same memory). Deep copy allocates new memory for dynamic members, ensuring independent objects.
A virtual destructor ensures that when a derived class object is deleted through a base class pointer, the derived class destructor is called first, followed by the base class destructor, properly cleaning up all resources.
Both references and pointers can be used for polymorphism in C++. References are generally safer (no null references, cannot be reassigned) while pointers are more flexible (can be null, reassigned).
In multiple inheritance, if both base classes have the same method, the derived class must either override it or use the scope resolution operator (A::foo() or B::foo()) to specify which one to call.
The diamond problem occurs when a derived class inherits from two classes that have a common base. Virtual inheritance ensures only one copy of the base class is created.
class A { public: virtual void print() { cout print(); }
With virtual functions and dynamic binding, arr[0]->print() calls A's print (outputs 'A'), and arr[1]->print() calls B's overridden print (outputs 'B'). Result: 'AB'.
When dynamic_cast fails on a pointer, it returns nullptr. For references, it throws a std::bad_cast exception.