suppose we have a function like below
Car buyCar();
My question is which method we must have in Car class for this function to work ? Is it default constructor ?
Car buyCar();
does not have the effect people think, look up "The Most Vexing Parse": https://en.wikipedia.org/wiki/Most_vexing_parse
Due to quirks in C++'s grammar, the syntax Type instance()
is actually interpreted as a declaration instead of as an invocation. See calling the default constructor
To call the default, parameterless, constructor of a type you need to omit the parenthesis.
Car buyCar; // allocates and constructs a `Car` on the stack
However, if you're allocating on the heap (with new
), then using the parenthesis does work.
Using raw pointers:
Car* buyCar = new Car();
Using smart pointers:
unique_ptr<Car> buyCar = make_unique<Car>(); // <-- parens used because this is actually calling `make_unique` (a function) which indirectly calls the constructor
In an initialization list, then you do use parenthesis to call the default constructor of a field - however this is largely pointless as the default (compile-generated) constructor for the type will already do this:
class Inner {
public:
Inner() {
}
}
class Container {
private:
Inner innerInstance;
public:
Container() :
innerInstance() // <-- parens used here
{ }
}
This method should return the object of the Car class. Default constructor is automatically available, it needs not to be defined separately. Custom constructor can also be created and initialized with required values. So, either you can return the default constructor or custom constructor based upon the requirements.
I have written a small example for you
#include <iostream>
using namespace std;
class Car {
public :
Car(): carnum(0) {
cout << "default constructor " << carnum << endl;
}
Car (int n) : carnum (n) {
cout << "Argument constructor " << carnum << endl;
}
Car& operator = (const Car& car) {
carnum = car.carnum;
cout << "operator = " << carnum << endl;
return *this;
}
Car (const Car& car) {
carnum = car.carnum;
cout << "Copy constructor " << carnum << endl;
}
Car buyCar() {
return *this;
}
int carnum;
};
int main() {
Car aCar, theCar(2); // default constructor for aCar and argument constructor for theCar;
cout << endl;
aCar = theCar.buyCar(); // copy constructor and equal operator are called
cout << endl;
Car bCar(aCar.buyCar()); // only copy constructor is called here
cout << endl;
return 0;
}
So, it depends on the context how you are using buyCar()
function.
I have assumed that buyCar()
is a member function of class Car
Even if class Car
do not have Constructors
and Assignment Operator
, the function buyCar()
would still work with default constructors and assignment operators.
But if your class deals with dynamic memory, that if the class has some data members which are dynamically created/allocated then the class should have the Copy Constructor
, Move Constructor
, Assignment Operator
and Move Assignment operator