I followed the youtube tutorial and i can create basic class but the tutorial doesn't explain how the Class::Class works, I search google but i only know that it is called unary operator and what it does but I dunno what it do with Class, please help me explain about this and thanks very much.
#include <iostream>
#include <string>
//Class
class Mother {
public:
void msg();
};
void Mother::msg(){ //This is where i don't undrstand
std::cout << "Go home early sweetie" << std::endl;
}
class Daughter: public Mother {
public:
void getMsg();
};
void Daughter::getMsg(){ //Same as this
std::cout << "Mom said ";
msg();
}
//Main
int main() {
Daughter lucy;
lucy.getMsg();
return 0;
}
In your class, you declare a member function msg()
, but you don't actually define it there:
class Mother {
public:
void msg();
};
Usually this declaration goes into a .h file, and now you want to put the function definition in a .cpp file. But you can't just write
void msg()
{
// ..
}
in your .cpp file, as this would define a global function, not a member function. Also, the compiler cannot know that you are really trying to define the member function, as several classes could be declared at this point. So you need a way to tell the compiler that the function lives inside the Mother
class:
void Mother::msg()
{
//..
}
The same syntax is used for namespaces. Take the class string
from the std
namespace:
std::string myString;
EDIT: A special function is the constructor, which has the same name as the class. The definition would look like this:
Mother::Mother()
{
// ..
}
In this constructor, you can initialize member variables and generally set up the class instance. All member variables are created at that point. Now what if you have a member variable of a type where you want to pass an argument to its constructor? Say you have a member var
with a constructor that takes an int
:
Mother::Mother() :
var(1)
{
// ..
}
So the constructor of var
is called before the body of the constructor of Mother
, and you can pass arguments to it.