Hi guys. I was wondering if this was legal or what would it do? So, I declared two classes. but inside each class has the same member function (they have the same names). So, are they considered different from each other? Say if I were to use the int getSpeed() of the Car object, would it use the Motorcycle one by accident? Thanks.
# include <iostream>
class Motorcycle
{
public:
int getSpeed();
};
class Car
{
public:
int getSpped();
};
to be continues.
Each variable can only be in each scope once, the variables in motorcycle and car are in 2 different scopes, so it is allowed. Variables are local to the scope of the bracket enclosing it, and fall out of scope outside of that.
1 2 3 4 5 6 7 8 9
int x; //global, has scope everywhere
int main()
{
int y; //Local to main only
{ //brace just cuz
int z; //local to only this inner brace
}
z = 3; //error, there is no z in this scope
}
Oh I get it now.
Also, I forgot that when you use a classes' function, you have to write the object's name then a dot then the name of the function such as
First of all hellohellomoon those methods (a method is a member function) have different names, but I assume int getSpped(); //line 12? is a typo... Anyway, even though the functions look like they have the same name, that is:
1 2 3 4 5 6 7
class A {
_ method(); //method named "method", member of class "A"
};
class B {
_ method(); //method named "method", member of class "B"
};
The names are not really the same to the compiler. Members of classes get a pseudo-obfusticated name just like members of namespaces do. For example:
1 2 3 4
namespace MySpace {
_ a; //variable's name looks like "a", but is really "MySpace::a"
class C; //class's name is "MySpace::C"
}
So in the first case of classes A and B, the method's names were really "A::method" and "B::method". Now note that even though their names are in the format of Class::name, because they are member functions (as opposed to static functions/methods) you would invoke them uniquely via an instance of the respective class. I.e.
1 2 3 4 5
A a;
B b;
a.method(); //invokes A::method
b.method(); //invokes B::method
A::method(); //Error, A::method is not static!
Thanks Mathhead200! Your post helped me classification and the importance of different scopes even more. Oh, and yeah that was a typo; sorry about that. I will double check my future posts.