C++ Tutorials: Switches and Classes[/u

In this tutorial we will be covering classes. We have talked about classes before but never really learned how they work. A switch statement though is different and we haven’t talked about them yet.

A class looks like this

Code

class SomeName
{
public:
     //public functions
private:
    //private functions
}




the statement:

Code

class SomeName




defines a class with the name: SomeName

Code

public:




is used for methods which are accessible outside of the class. This does not mean you can’t call a public function or variable from within the class though. You can do that.

Code

private:




is used for functions accessible inside of the class. These are used internally and if tried to be used outside of the class will create a compile error.

Inheritance:

Classes have a unique feature. Here is an example demonstrating this:

Code

class InheritanceClass
{
public:
    void method();
}

class OtherClass : public InheritanceClass
{
public:
    void someOtherMethod();
}

InheritanceClass::method();
OtherClass::method();
OtherClass::someOtherMethod();




Notice that method(); was not defined in OtherClass but was defined in InheritanceClass. Inheriting means that if you have one class and it inherits from another you will be able to access those in that other class. To make a class inherit from another you use colon ( : ) public ClassName, replacing class name with the class you want this class to inherit from.

Now for the switch statement. A switch statement is similar to an if statement but more efficient when used well and looks much nicer.

Code

int i = 2;

switch(i)
{
case 0:
    //Do something when i  is 0
    break;
case 1:
    //Do something when i is 1
    break;
case 2:
   //Do something when i is 2
    break;
}




Notice another new thing:

break;

Break is used to break out of loops, and switches. If you do not have a break in the switch statement it will continue and check if that variable (in this case i) is equal to case :

That concludes this tutorial. In the Next one we will discuss While, and For loops.

What Do You Think on This ? Say Here

This site uses Akismet to reduce spam. Learn how your comment data is processed.