naval
naval

Reputation: 1413

Class constructor error

Since we know that constructor is not inherited in the child class as i asked in the my previous question Click here to view question

I had write the code

namespace TestConscoleApplication
{
    abstract public class A
    {
       public int c;
       public int d;

    private  A(int a, int b)
       {
           c = a;
           d = b;

       }
        public virtual void Display1()
        {
            Console.WriteLine("{0}{1}", c, d);
        }
    }
    internal class B : A 
    {
      protected  string Msg;

      public B(string Err)

        {
            Msg = Err;

        }

        public  void Display()
        {
            Console.WriteLine(Msg);
        }
    }



    class Program
    {
        static void Main(string[] args)
        {
            B ObjB = new B("Hello");


            Console.ReadLine();
        }
    }
}

when i compile the code its showing an error

Error TestConscoleApplication.A.A(int, int) is inaccessible due to its protection level.

Then why it is showing an error.

Upvotes: 1

Views: 117

Answers (4)

Eren Ersönmez
Eren Ersönmez

Reputation: 39085

By making the only constructor of A private, you've prevented derived classes from being able to be constructed outside A.

Upvotes: 4

Tim S.
Tim S.

Reputation: 56536

You need to have a constructor for A accessible to B, and use it. Also, the default base constructor is base() (i.e. the parameterless constructor), which doesn't exist on A. Here's one way you can resolve this (nonessential bits removed):

abstract public class A
{
    protected A(int a, int b)
    {
    }
}
internal class B : A
{
    public B(int a, int b, string Err)
        : base(a, b)
    {
    }
}

Upvotes: 0

yogi
yogi

Reputation: 19591

constructors shouldn't be private otherwise you will not be able to create an instance of that class and won't be able to inherit it too, but if you want to create a private constructor create a public one with it too. For more info Go here

Upvotes: -1

Ivan Nikitin
Ivan Nikitin

Reputation: 4133

Derived class constructor always call the base constructor (one of). Making it private you prohibit access to it from outside. In other words you make it impossible to make an instance of A outside A.

Since you made a constructor, the compiler won't generate a default public one for this class for you.

If you want to provide access to it from the class descendant but not from outside, you should make it protected.

Upvotes: 1

Related Questions