Q- Write constructors of class A and Class B to initialize class A’s variable int a, when we create the derived class object i.e. object B ob = new B(5); in main().
class A
{
int a;
// write class A constructor
}
class B : A
{
//write class B constructor
}
class Program
{
static void Main(string[] args)
{
B ob = new B(5);
}
}
Answer: Complete program below with comments. We have to use “base” keyword in derived class constructor to pass data to base class constructor via derived class constructor.
class A
{
int a;
public A(int j)
{
a = j;
}
}
class B : A
{
//use "base" keyword to pass the value to clas A constructor.
public B(int j): base(j)
{
}
}
class Program
{
static void Main(string[] args)
{
//pass int value 10 to initialize
//base class A variable int a;
B b = new B(5);
}
}