0
What is the Error (if any) in the below C++ code
class TestClass { public: // Constructors TestClass():x(0) { } TestClass(int a):x(a) { } void printValue() { std::cout<< "Value :"<<x; } private: int x; }; int main() { TestClass obj(); obj.printValue(); }
1 Answer
0
Solution:
If we want to define an object of a class which uses default constructor then the object need to be defined as below
TestClass obj; // and NOT obj()
We are creating object in our code as
TestClass obj();
This is not creating an object, but declaring a function(prototype) obj whose return type is TestClass.
This is the problem, Since obj is not the object of class TestClass, calling function printValue using obj will give error. Hence the statement
obj.printValue();
Is an Error, but the reason is the attempt to create object in the previous statement.
When you want to create object of a class which uses 1 argument constructor (also called type-convertor constructor), the object is defined in one of the two ways:
TestClass obj(2); // Like a function call
TestClass obj = 2;