Im studying classes and have questions regarding this sample code that was given in the tutorial section.
1)What is this line of code? int area() {return width*height;}
2)When declaring a function that is to be used in the class why is :: being used?
3)How do you declare something to fall underneath the created class? Rectangle rect;? Can you not simply call the class like you would a function? Any tips on how to utilize classes.
1) the method int area() {return widht*height} is nothing else than
1 2 3 4
int Rectangle::area()
{
return width * height;
}
2) Dunno... Just do it ;) Those :: can be used for static objects as well! (Forget it if it confuses you)
3) Creating a class is like creating a new datatype (e.g. int / bool / float / double......). You are creating a datatype called Rectangle. How do you declare new variables?
1 2 3 4
Datatype Variablename;
int Width;
Rectangle Rect; //<-- A new object of type Rectangle
When your Declaration isnt a pointer, you use the "." Operator to Access functions from this datatype.
If your Declaration is a pointer, you use the "->" Operator to Access the function...
Classes are making c++ a OOP (Object Oriented Programming)-language and will be veeeeery useful in your future ;)
1)What is this line of code? int area() {return width*height;}
you can actually define a member function that is use to set a value inside the class
2)When declaring a function that is to be used in the class why is :: being used?
::operator is use to link the declaration and definition of a class.
it is like a prototype and the :: operator is use to define of a function
Rectangle rect;? Can you not simply call the class like you would a function?
well , you can simply call a function that is declared(prototype) at the top of the main function because it is global ( global scope ).
but how do you call function that comes from another files? simply, you should include the header where that function is declared because it has a difference scope ( file scope )
but definitely this is not the reason why you create an object.
class Wibble
{
.....
};
int main()
{
Wibble w1;
Wibble w2;
Wibble w3;
Wibble w4;
// you now have FOUR objects. Your Wibble class (of
// which you have one and always one) is the
// thing that creates them
}