So I get the whole class symntex and everything for classes BUT the thing i dont get is the constructor.. i dont get it. I know it initalizes your members I think when you define them when creating the classes in the .h file BUT when your going into the .CPP file for that specific class you gotta out things in the constructor right? like for example after defining the class type you go into your specific .cpp file and look into your construct and it says this
1 2 3 4 5 6 7 8
phone::phone()
{
// defined varabiles right? what about during execution cant really define those
}
sound like a dumb question but I guess you would define variables in there but what about if you need input from the user while the program is executing? Like if the program asks what kind of phone? what kind of model? when did you get it (date)? hope this makes sense sorry if it doesnt and I will try and explain better if it doesnt.
You don't actually define your variables in the constructor. You initialize them. Every time you create a new object of your class the constructor is called to give its member variables initial values.
In the context of classes, the constructor is invoked (called) when the class is instantiated. The constructor is used to initialize the members of the class before any function or variable touches them, assuming they have access in the first place. The destructor does the exact opposite of the constructor; it destroys the members within the class as soon as the object (the name given to a class instantiation) goes out of scope. The destructor is the last to be invoked.
class MyClass
{
int i; // define variable i
public:
MyClass() // constructor
{
i = 9; // initialize i with the value 9 here
}
};
int main()
{
MyClass mc; // create an object of type MyClass (the constructor runs now);
}
Taking your code from above, and changing line 15, am I effectively initializing the variable (I) with the value 10 instead of 9? Is this called overloading?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class MyClass
{
int i; // define variable i
public:
MyClass() // constructor
{
i = 9; // initialize i with the value 9 here
}
};
int main()
{
MyClass mc (10); // create an object of type MyClass (the constructor runs now);
}
Not quite, you are thinking of assigning it, the constructor can take parameters like functions, but you need to tell it what to use:
MyClass(int c)
i = c; // initialize i with the value c here
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class MyClass
{
int i; // define variable i
public:
MyClass(int c) // constructor
{
i = c; // initialize i with the value c here
}
};
int main()
{
MyClass mc (10); // create an object of type MyClass (the constructor runs now);
}