Skip to content
Prashant edited this page Nov 22, 2019 · 7 revisions

Overloading doesn’t work for the derived class in the C++ programming language. There is no overload resolution between Base and Derived. The compiler looks into the scope of Derived, finds the single function “double f(double)” and calls it. It never disturbs the (enclosing) scope of Base.

In Java overloading works across scopes contrary to C++. Java compiler determines the correct version of the overloaded method to be executed at compile time based upon the type of argument used to call the method and parameters of the overloaded methods of both these classes receive the values of arguments used in call and executes the overloaded method.

Almost all operators can be overloaded except few. Following is the list of operators that cannot be overloaded.. (dot),:: ?:, sizeof


What is the difference between new and malloc()? the malloc() is a function that takes a number (of bytes) as its argument; it returns a void* pointing to uninitialized storage. new is an operator that takes a type and (optionally) a set of initializers for that type as its arguments; it returns a pointer to an (optionally) initialized object of its type. The difference is most obvious when you want to allocate an object of a user-defined type with non-trivial initialization semantics.


Why are destructors not virtual by default? Because many classes are not designed to be used as base classes. Virtual functions make sense only in classes meant to act as interfaces to objects of derived classes (typically allocated on a heap and accessed through pointers or references). So when should I declare a destructor virtual? Whenever the class has at least one virtual function. Having virtual functions indicate that a class is meant to act as an interface to derived classes, and when it is, an object of a derived class may be destroyed through a pointer to the base.


What is a pure virtual function? A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be "pure" using the curious "=0" syntax. For example:


What is a copy constructor? A copy constructor is a member function that initializes an object using another object of the same class. A copy constructor has the following general function prototype:

`ClassName (const ClassName &old_obj); `

When is copy constructor called? In C++, a Copy Constructor may be called in the following cases:

  1. When an object of the class is returned by value.
  2. When an object of the class is passed (to a function) by value as an argument.
  3. When an object is constructed based on another object of the same class.
  4. When the compiler generates a temporary object.

When is user-defined copy constructor needed? If we don’t define our own copy constructor, the C++ compiler creates a default copy constructor for each class which does a member-wise copy between objects. The compiler created copy constructor works fine in general. We need to define our own copy constructor only if an object has pointers or any runtime allocation of the resource like filehandle, a network connection..etc.

Default constructor does the only shallow copy.

Deep copy is possible only with the user-defined copy constructor.


Can we make copy constructor private? Yes, a copy constructor can be made private. When we make a copy constructor private in a class, objects of that class become non-copyable. This is particularly useful when our class has pointers or dynamically allocated resources. In such situations, we can either write our own copy constructor like above String example or make a private copy constructor so that users get compiler errors rather than surprises at runtime.


Why argument to a copy constructor must be passed as a reference? A copy constructor is called when an object is passed by value. The copy constructor itself is a function. So if we pass an argument by value in a copy constructor, a call to copy constructor would be made to call copy constructor which becomes a non-terminating chain of calls. Therefore compiler doesn’t allow parameters to be passed by value.


Friend Class A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private members of another class. friend class LinkedList; friend int LinkedList :: search();

Friendship is not inherited. The concept of friends is not there in Java.


Enum doesn’t allow implicit conversion to int, and also doesn’t compare enumerators from different enumerations.

Some interesting facts about static member functions in C++ :

  • static member functions do not have this pointer.
  • A static member function cannot be virtual
  • Member function declarations with the same name and the name parameter-type-list cannot be overloaded if any of them is a static member function declaration.For example, following program fails in compilation with error “‘void Test::fun()’ and `static void Test::fun()’ cannot be overloaded ”
  • A static member function can not be declared const, volatile, or const volatile.

This pointer is available to each member function as a hidden implicit argument. It is the object address value as a pointer. For static functions, there is no object address at all because the static function can be called even before the creation of any object using a scope resolution operator. Even calling with an object pointer will not associate any "this" pointer to it. Thus this pointer is not available in any static function.


Virtual functions in derived classes In C++, once a member function is declared as a virtual function in a base class, it becomes virtual in every class derived from that base class. In other words, it is not necessary to use the keyword virtual in the derived class while declaring redefined versions of the virtual base class function.


Can we make a class constructor virtual in C++ to create polymorphic objects? No. C++ being statically typed (the purpose of RTTI is different) language, it is meaningless to the C++ compiler to create an object polymorphically. The compiler must be aware of the class type to create the object. In other words, what type of object to be created is a compile-time decision from the C++ compiler perspective. If we make constructor virtual, compiler flags an error. In fact, except inline, no other keyword is allowed in the declaration of the constructor.


virtual constructor creates an object of class hierarchy at runtime based on some input. When we want to copy construct an object from another object created by the virtual constructor, we can’t use a usual copy constructor. We need a special cloning function that can duplicate the object at runtime. As an example, consider a drawing application. You can select an object already drawn on the canvas and paste one more instance of the same object. From the programmer's perspective, we can’t decide which object will be copy-pasted as it is runtime decision. We need a virtual copy constructor to help. Similarly, consider the clipboard application. A clipboard can hold different types of objects, and copy objects from existing objects, paste them on application canvas. Again, what type of object to be copied is a runtime decision. Virtual copy constructor fills the gap here

Virtual destructor Deleting a derived class object using a pointer to a base class that has non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor. Making base class destructor virtual guarantees that the object of a derived class is destructed properly, i.e., both base class and derived class destructors are called. As a guideline, any time you have a virtual function in a class, you should immediately add a virtual destructor (even if it does nothing).

class base { public: base() { cout<<"Constructing base \n"; } virtual ~base() { cout<<"Destructing base \n"; } }; class derived: public base { public: derived() { cout<<"Constructing derived \n"; } ~derived() { cout<<"Destructing derived \n"; } };


Pure Functions A function is called pure function if it always returns the same result for the same argument values and it has no side effects like modifying an argument (or global variable) or outputting something. The only result of calling a pure function is the return value. Examples of pure functions are strlen(), pow(), sqrt() etc. Examples of impure functions are printf(), rand(), time(), etc. __attribute__ ((pure)) return-type fun-name(arguments1, …) {body}

Can a destructor be pure virtual in C++? Yes, it is possible to have a pure virtual destructor. Pure virtual destructors are legal in standard C++ and one of the most important things to remember is that if a class contains a pure virtual destructor, it must provide a function body for the pure virtual destructor. You may be wondering why a pure virtual function requires a function body. The reason is that destructors (unlike other functions) are not actually ‘overridden’, rather they are always called in the reverse order of the class derivation. This means that a derived class’ destructor will be invoked first, then base class destructor will be called. If the definition of the pure virtual destructor is not provided, then what function body will be called during object destruction? Therefore the compiler and linker enforce the existence of a function body for pure virtual destructors. It is important to note that a class becomes an abstract class when it contains a pure virtual destructor.

public: virtual ~Test()=0; // Test now becomes abstract class }; Test::~Test() { }

Pure Virtual Functions and Abstract Classes in C++ Sometimes implementation of all functions cannot be provided in a base class because we don’t know the implementation. Such a class is called an abstract class. For example, let Shape be a base class. We cannot provide the implementation of function draw() in Shape, but we know every derived class must have the implementation of draw(). Similarly, an Animal class doesn’t have the implementation of the move() (assuming that all animals move), but all animals must know how to move. We cannot create objects of abstract classes.

A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have an implementation, we only declare it. A pure virtual function is declared by assigning 0 in the declaration.

  • A class is abstract if it has at least one pure virtual function.
  • We can have pointers and references of abstract class type.
  • If we do not override the pure virtual function in derived class, then derived class also becomes an abstract class.
  • An abstract class can have constructors.

Inheritance is one in which a new class is created that inherits the properties of the already existing class. It supports the concept of code reusability and reduces the length of the code in object-oriented programming. Types of Inheritance are:

  • Single inheritance
  • Multi-level inheritance
  • Multiple inheritances
  • Hybrid inheritance
  • Hierarchical inheritance

Polymorphism is that in which we can perform a task in multiple forms or ways. It is applied to the functions or methods. Polymorphism allows the object to decide which form of the function to implement at compile-time as well as run-time. Types of Polymorphism are:

  • Compile-time polymorphism (Method overloading)
  • Run-time polymorphism (Method Overriding)

In C++, virtual functions can be private and can be overridden by the derived class.

Can virtual fnc be inlined Virtual functions are used to achieve runtime polymorphism or say late binding or dynamic binding. Inline functions are used for efficiency. Whenever a virtual function is called using base class reference or pointer it cannot be inlined (because the call is resolved at runtime), but whenever called using the object (without reference or pointer) of that class, can be inlined because the compiler knows the exact class of the object at compile time.

Virtual functions allow us to create a list of base class pointers and call methods of any of the derived classes without even knowing kind of derived class object. For example, consider an employee management software for an organization. Let the code has a simple base class Employee , the class contains virtual functions like raiseSalary(), transfer(), promote(), etc. Different types of employees like Manager, Engineer, etc. may have their own implementations of the virtual functions present in base class Employee. In our complete software, we just need to pass a list of employees everywhere and call appropriate functions without even knowing the type of employee. For example, we can easily raise the salary of all employees by iterating through the list of employees. Every type of employee may have its own logic in its class, but we don’t need to worry about them because if raiseSalary() is present for a specific employee type, only that function would be called.


Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. Another way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield. As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.

  • While encapsulation is the process or method to contain the information.
  • While in encapsulation, problems are solved at the implementation level.
  • encapsulation can be implemented using by access modifier i.e. private, protected and public.
  • in encapsulation, the data is hidden using methods of getters and setters.

Data Abstraction is the property by virtue of which only the essential details are displayed to the user. The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components. Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details. The properties and behaviours of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects.

  • Abstraction is the method of hiding the unwanted information.
  • Abstraction is the process or method of gaining the information.
  • In abstraction, problems are solved at the design or interface level.
  • We can implement abstraction using abstract class and interfaces.
  • In abstraction, implementation complexities are hidden using abstract classes and interfaces.
Clone this wiki locally