Answer: Here is the difference between constructor and member function in C++ programming.
- Constructor name must be same as class name but functions cannot have same name as class name.
C++ Code Example :
12345678910111213141516class Car{int count;public://This constructor has same name as class nameCar(){}//function cannot have same name as classvoid CarAvailable(){}}; - Constructor does not have return type whereas functions must have.
C++ Code Example :
1234567891011121314151617181920class Car{int count;public://Constructor :- No return typeCar(){}//@return type int, in C++ function must have return type// it can also be void type, means return nothing, but must mention its type.int CarAvailable(){return count;}void CarSold(){}}; - Member function can be virtual, but, there is no concept of virtual-constructor in C++. ( NOTE: virtual destructor to maintain destructor call order in inheritance is available in C++ language)
C++ Code Example :
1234567891011121314151617class Car{int count;public://Constructor :- Can never be VIRTUAL,No provision.Car(){//}//Function can be virtual, so that it can be overriden in derived classes.virtual void CarAvailable(){}}; - Constructors are invoked at the time of object creation automatically and cannot be called explicitly but functions are called explicitly using class objects.
C++ Code Example :
12345678910111213141516171819202122232425262728class Car{public:Car(){cout << "Car's Constructor\n";}void CarAvailable(){cout << "Car's Function\n";}};int main(){//Constructor will be invoked automatically//during object creation.Car obj;//Functin can be called using class object, no automaticobj.CarAvailable();return 0;}