Dalldorf Design Home Portfolio Pricing Services Resume About Tutorials
 
                                  Simple Class Inheritance

 Source Files  Simple Class Inheritance


In this tutorial you will learn how to create classes and use inheritance. This code was written with Visual Studio 2005 and used the win32 Console application. I only included the .cpp file so you can download and run it in whatever program you use.
First you need to create the classes. For this excersize we will call them level3, level2, level1.

class level3
{
       public int num3;
       public level3()
       {
             num3 = 10;
       }
       public int Add(int addNum)
       {
            return num3 + addNum;
       }
}

class level2 : level3
{
        public int num2;
        public level2()
        {
             num2 = num3;
        }
        public int Subtract(int subNum)
        {
             return num2 - subNum;
        }
}

class level1 : level2
{
        public int num1;
        public level1()
        {
             num1 = num2;
        }
        public int AddSubtract(int AddNum, int subNum)
        {
             return (Add(AddNum) + Subtract(subNum));
        }

        public static void Main(string[] args)
        {
                level1 levelInheritance = new level1();
                Console.WriteLine(levelInheritance.num1);
                Console.WriteLine(levelInheritance.num2);
                Console.WriteLine(levelInheritance.num3);
                Console.WriteLine(levelInheritance.Add(10));
                Console.WriteLine(levelInheritance.Subtract(10));
                Console.WriteLine(levelInheritance.AddSubtract(30,20));
                Console.ReadLine();
        }
}

As you can see, class level1 inherits the properties of class level2 and class level2 inherites from class level3. I am not going to go into detail on this code, but I recommend expanding on it by adding diffrent functions and and data types. Also explore using private variables and methods.


 
Copyright © 2007 Dalldorf Design. All Rights Reserved