Home > Development > Comparison of C++ and C# Inheritance

Comparison of C++ and C# Inheritance


This is going to be a fairly basic post showing how to do inheritance in C++ if you have a C# background.
Well onto the code.

#include <iostream>
#include <string>
#include <typeinfo>

using namespace std;

class Super
{
protected:
    int value;
public:
    Super();
    Super(int number);
    int getValue() const;
    void setValue(int number);
    virtual void printToStandardOut() const;
};

Super::Super(){
    value = 0;
}

Super::Super(int number){
    value = number;
}

int Super::getValue() const{
    return value;
}

void Super::setValue(int number){
    value = number;
}

void Super::printToStandardOut() const{
    cout << "The value is " << value << endl;
}

class Sub : public Super
{
public:
    Sub();
    Sub(int number);
    void printToStandardOut() const;
};

Sub::Sub() : Super(0){

}

Sub::Sub(int number) : Super(number){

}

void Sub::printToStandardOut() const{
    cout << "The new value is " << (value * 10) << endl;
}

int main(int argc, char *argv[])
{
    Super* super = new Super(10);
    Super* ref = new Sub(10);

    super->printToStandardOut();
    ref->printToStandardOut();

    delete super;
    delete ref;
    return 0;
}

Here is the same class in C#

using System;

namespace CSharpClasses
{

	public class Super{
		protected int value;
		public Super(){
			
		}
		
		public Super(int value){
			this.value = value;
		}
		
		public int GetValue(){
			return value;
		}
		
		public void SetValue(int value){
			this.value = value;
		}
		
		public virtual void PrintToStandardOut(){
			Console.WriteLine("The value is {0}",value);
		}
		
	}
	
	public class Sub : Super{
		public Sub() : base(10){}
		public Sub(int value) : base(value){}
		public override void PrintToStandardOut ()
		{
			Console.WriteLine ("The value is {0}", value * 10);
		}
		
	}

	class MainClass
	{
		public static void Main (string[] args)
		{
			Super sp = new Super(10);
			sp.PrintToStandardOut();
			
			Super sb = new Sub(10);
			sb.PrintToStandardOut();
		}
	}
}

Blair…..

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: