Inheritance

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am attempting to learn OOP. The book uses C++ examples. I am trying to
convert the code to C#. C# doesn't like the statement Person::Display(); in
the Student class. How do I need to modify this to work in C#? Thanks for
your help.

using System;

namespace LevelInheritance
{
public class Person
{
protected int m_ID;
protected string m_First;
protected string m_Last;

public Person()
{

m_ID = 0;
m_First = "\0";
m_Last = "\0";
}

public virtual void Display()
{
Console.WriteLine("ID: " + m_ID +
"\rFirst: " + m_First +
"\rLast: " + m_Last);
}

public void Write(int ID, string First, string Last)
{
m_ID = ID;
m_First = First;
m_Last = Last;
}
}

class Student: Person
{
protected int m_Graduation;

public override void Display()
{
Person::Display();
Console.WriteLine("Graduation: " + m_Graduation);
}


public void Write(int ID, string First, string Last, int Graduation)
{
Write(ID, First, Last);
m_Graduation = Graduation;
}

public Student()
{
m_Graduation = 0;
}
}
 
I receive an error with the dot also. The error is below

An object reference is required for the nonstatic field, method, or property
'LevelInheritance.Person.Display()'
 
You have to understand what is an instance and what is a static method.
If person or display is an instance property then you have to create an
instance of the object (ie, new ...)
 
C# doesn't like the statement Person::Display(); in
the Student class. How do I need to modify this to work in C#?

You use the base keyword to call the base class' implementation of a
virtual method from an override.

base.Display();

Since C#, unlike C++, only supports a single base class, there's no
need to explicitly name it.


Mattias
 
From the context it looks like it was trying to call the Display()
method of the Person class , followed by specific class code - this
makes sense as :: is used as a scope qualiifer in C++

For this, you would use

base.Display();

instead of

Person::Display();


hth,

Alan.
 
Back
Top