Why do they always use the name of the class when declaring an object inside the class? | SoloLearn: Learn to code for FREE!

0

Why do they always use the name of the class when declaring an object inside the class?

It really confuses me when they create a class named MyClass, then create an object MyClass inside of it. They're separate ideas, right? Or am I missing a concept completely?

8/16/2016 3:16:14 PM

Adam Mullenaux

7 Answers

New Answer

+2

Ah, that's a constructor :) In this case, it means MyClass's may be created so long as two int's are passed into it on creation. Somewhere in the corresponding cpp file will be some code declaring what the constructor does.

+1

Could you copy the code here?

+1

Oh man, I made it through an entire module thinking that they were creating an object and simply not using it, in every lesson. Guess I should revisit these lessons without this oversight

+1

@Adam that's not a public object but a public member function known as constructor. The expressions within a class serve as a blueprint for creating objects. The member functions of a class known as methods are properties of the object when created. Example of object created is MyClass obj created in the main function

0

class MyClass { public: MyClass(int a, int b); private: int regVar; const int constVar; }; The first thing they do after naming the class is to create a public object named MyClass. Is it not an object being created?

0

That MyClass(int a, int b) function is not an actual instruction. It does not happen when you write it, within the class it just tells the program how to create the class when it's being run. It's like... The class is a cake and the function you're referring to is a cake recipe, while your daily routine is contained within the int main() {whatever } function. Only when in the main program you call a constructor Myclass(x, y) does the cake get created and passed to the rest. Actual code for having a cake would be int main() { cake MyClass(5,7); cake.doSomething(); }

0

This course is very good, but not very detailed. Look up for class constructor and destructor. Class can have many constructor functions and one of the constructor gets called automatically when a class object is created.