Hello Joe!
Well, the first 2 methods, A and B, refer to accessing the variables or functions inside a class.
For example:
1 2 3 4 5 6 7 8 9 10 11
|
class Car
{
public:
Car(string Name, int Max_speed, int Color); // constructor
~Car() {}; // deconstructor
string name; // the name of the car
int max_speed; // the max speed
int color; // the color of the car
void start_engine(); // function that starts the engine
void stop_engine(); // function that stops the engine
}
|
Now if you make objects of type car:
1 2 3 4 5 6
|
Car Volvo( "Volvo", 120, 0); // this is a statically allocated object
Volvo.start_engine(); // because it is staticcaly allocated you use the '.' operator to refer to its variables or functions
Car *Renault = new Car( "Renault", 120, 2); // this is dinamically allocated object
Renault->start_engine(); // because it is dinamically alocated you use the '->' operator instead, to refer to properties or methods
|
The third option, C, refers to the scope operator
::
and has to do with namespace.
For example let's say you want to define the 4 methods inside the class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
class Car
{
public:
Car(string Name, int Max_speed, int Color); // constructor
~Car() {}; // deconstructor
string name; // the name of the car
int max_speed; // the max speed
int color; // the color of the car
void start_engine(); // function that starts the engine
void stop_engine(); // function that stops the engine
}
Car::Car(string Name, int Max_speed, int Color)
{
name = Name;
max_speed = Max_speed;
color = Color;
}
void Car::start_engine() // you use the scope operator to specify that the function is from a certain class
{
//whatever source code
}
void Car::stop_engine()
{
//whatever source code
}
|
As you can see, you use the scope operator to tell the compiler from wich class that function is, in case you have the same name of functions in 2 or more classes and you want to be able to still differentiate between functions.Like bellow:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
class Car
{
string name;
int max_speed;
void start_engine();
void stop_engine();
}
class Plane
{
string name;
int max_speed;
void start_engine();
void stop_engine(); // be carefull with this one :)
}
void Car::start_engine() // this is the start_engine() function from the Car class
{
//whatever source code
}
void Plane::start_engine() // this is the start_engine() function from the Plane class
{
//whatever source code
}
|
So remember:
.
and
->
are for accessing properties or method of a class (or object of that type)
::
is to specify from what class or namespace (you could just have a namespace) is that variable or function from.