I’m very new to c++, please help me to figure out how these operators work
class MyCalss : public State // MyClass inherits State?
{
private
MyClass(){} // Constructor for MyClass?
MyClass(const MyClass&); // const means that invoking object will be not changed? What the meaning of '&' symbol? MyClass&
MyClass& operator = (const MyClass&) // What this statement exactly do? is it some kind operation overloading?
}
For example I have constructor
MyClass2::MyClass2(int i):BaseEntity(id),
m_iTotal(5),
m_iMonye(5),
m_iLevel(10){}
What is :BaseEntity(id) here means?
and can I rewrite it like this?
MyClass2::MyClass2(int i):BaseEntity(id)
{
m_iTotal = 5;
m_iMonye = 5;
m_iLevel = 10;
}
Ok, taking your questions one at a time:
exactly so. MyClass inherits (publicly, which is usually the only kind of inheritance you care about) from State. Literally, MyClass “is a” State – everything true about State is also True about MyClass.
Yes,
MyClass(){}is a constructor for MyClass, specifically in this case taking no arguments and doing nothing (nothing special – memory will still be allocated, etc). However, because you’ve made MyClass()private, nothing else can call it, meaning you can’t ever create a MyClass object (with no parameters) except from within MyClass methods.Yes, const means that the object passed as a parameter won’t be changed. This is, in fact, the Copy Constructor – the special constructor used to create a MyClass as a clone of an existing object. Again, it’s private, so most of the world can’t call it. The
&indicates passing the parameter by reference – this prevents the compiler having to copy the object, and is often a good thing.This is the copy-assignment operator, used to allow statements like `instance_a = instance_b;”.
Note that, unless you define them yourself, the compiler will generate default versions of all of these three for you.
BaseEntity(id)is very similar to the other three lines; it’s telling the compiler that when MyClass2 is constructed, it should call the parent classBaseEntity‘s constructor with the parameterid. Your second form of this constructor is very similar to your first form, but the first one – using an initialisation list – is considered better form.