0

Classes question.

Why this code does not compiles? #include <iostream> using namespace std; class MyClass { public: MyClass(); void myPrint(); }; MyClass::MyClass() { cout << " World"; } void MyClass::myPrint() { cout <<"Hello"<<endl; } int main() { MyClass obj; MyClass obj2; obj.myPrint(); obj2.MyClass(); } I didnt get what is MyClass() f. in class MyClass? Then what it is?

24th Jan 2017, 7:55 PM
Denis Zinkov
Denis Zinkov - avatar
6 Answers
+ 3
MyClass() is the constructor of MyClass and is called automatically once you create a MyClass object (MyClass obj; MyClass obj2; both call MyClass() ). It's not possible to call the constructor again, so the problem is "obj2.MyClass();"
24th Jan 2017, 8:05 PM
Robobrine
Robobrine - avatar
+ 1
I'm not quite sure what you mean. Can you show me the code that doesn't work?
24th Jan 2017, 8:26 PM
Robobrine
Robobrine - avatar
0
You define MyClass() in the public section in class MyClass, the compiler will search your code outside the class until it finds the MyClass::MyClass() function, doesn't matter where it is as long as it's after the class definition. Of course you could also just define MyClass() inside class MyClass.
24th Jan 2017, 8:14 PM
Robobrine
Robobrine - avatar
0
Its just a code from lesson. This code back there is to represent that function defenition type must be the same outside, as in class. Its all about void myPrint(). But I don't get why myPrint() works, and when I pasted the same code in empty ::MyClass() f and called it - it doesnt work. Wrong call or what. Or MyClass is an un touchable "monumant"?
24th Jan 2017, 8:22 PM
Denis Zinkov
Denis Zinkov - avatar
0
Robobrain. Just put under comments create and call of obj2. It works. But MyClass does not. Where to define it to make it work. Im about code in question.
24th Jan 2017, 8:32 PM
Denis Zinkov
Denis Zinkov - avatar
0
Oh. Damn. I got it. First answere was best, I just forgot some about constroctor.
24th Jan 2017, 8:48 PM
Denis Zinkov
Denis Zinkov - avatar