{} syntax in the Class code block | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

{} syntax in the Class code block

What is the purpose of the {} after the constructor and before a function in a Class? Thank you.

26th Nov 2019, 6:06 AM
Abraham Almerol
Abraham Almerol - avatar
4 Answers
+ 3
A constructor needs to have a body in which you can tell it what to do. It doesn't matter if it does not do anything but still it needs to have curly braces { }. Constructor is a method in general so it should have { }.
26th Nov 2019, 6:43 AM
Avinesh
Avinesh - avatar
+ 1
class MyClass2{ public: MyClass2(int a): var(a) {} // This is what I am referring to. What is this for? void printInfo(){ cout<<var<<endl; cout<<this->var<<endl; cout<<(*this).var<<endl; } private: int var; }; Thank you for the immediate response. But I still don't get it. Please see the code above to get in line with my thought. Thank you.
26th Nov 2019, 6:20 AM
Abraham Almerol
Abraham Almerol - avatar
+ 1
@Avinesh You are a gem! Thank you!
26th Nov 2019, 6:56 AM
Abraham Almerol
Abraham Almerol - avatar
0
Consider it as a container. You need a job to be done?, just put it inside { } with the required conditions to get the expected result.
26th Nov 2019, 6:10 AM
Avinesh
Avinesh - avatar