I'm having trouble distinguishing the differences when initializing objects using constructors.
I've also read that Bjarne recommends the {} syntax but that it's mostly equivalent to the () syntax so I think that I understand that part.
The problem occurs on line 40 with Car b();
.
#include <iostream>
#include <conio.h>
class Car
{
public:
Car() // initialize car
{
std::cout << "Default constructor called" << std::endl;
++carNumber;
}
~Car() // destroy car
{
--carNumber;
}
static int getCarNumber() { return carNumber; };
private:
static int carNumber;
};
int Car::carNumber = 0;
int main() {
// Equivalent
std::cout << "Car a{};" << std::endl;
Car a{};
std::cout << "Car d = Car{};" << std::endl;
Car d = Car{};
// Equivalent
std::cout << "Car e;" << std::endl;
Car e;
std::cout << "Car c = Car();" << std::endl;
Car c = Car();
std::cout << "Car b(); " << std::endl;
Car b(); // this line
std::cout << "CarNumber: " << Car::getCarNumber() << std::endl;
_getch();
return 0;
}
This is the output of the program:
Car a{};
Default constructor called
Car d = Car{};
Default constructor called
Car e;
Default constructor called
Car c = Car();
Default constructor called
Car b();
CarNumber: 4
I'm confused with "Car b()". I think the compiler is interpreting it as a funcition that returns a Car, but if that's the case I don't see where the function may be implemented (it should cause an error?").
I expected "Car b()" to call the default constructor I made but it doesn't.