-7

Look at the first class :

     class A

{
    public:
        int x;
        A(int v) { x=v; }
};

Also, take a look at class B ( i used inheritance )

class B : public A //Inheritance{
public:
    B(int v) :A(v) {y=v; }
    int y;
};

Now can you explain why we use :A (v)?, i know that the initializer list can be used to initialize member variables, but... constructors ?! . i think there's something about the initializer that i don't know, can you give me a good place to read about it ?

TheNewOne
  • 1
  • 2
  • Please, format your text properly. Try to copy the formatting from all the C++ books you have read. – DeiDei Jun 18 '18 at 10:26
  • 2
    Also, where does the `v2` in `y=v2;` in the child class come from? – Raghav Jun 18 '18 at 10:26
  • 1
    With what argument, the `Parent` constructor needs to be invoked, if you don't specify it? Consider learning from a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Algirdas Preidžius Jun 18 '18 at 10:27
  • The compilation error is due to the absence of a integer-parametered constructor. When you do `Child c(10);` there should be a constructor that matches the arguments. – Raghav Jun 18 '18 at 10:29
  • 1
    Possible duplicate of [What is this weird colon-member (" : ") syntax in the constructor?](https://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor) – Tadeusz Kopec for Ukraine Jun 18 '18 at 11:23

2 Answers2

3

Now can you explain why we use Child(int v):Parent (v)

Because that is how you initialize the superclass in C++ when it only has such a constructor.

When I delete it the program gives me a compilation error

Because you would then be implicitly calling the constructor Parent(), with no arguments, which doesn't exist, as your unstated compilation error undoubtedly states.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

Your program is ill-formed.

As per class.ctor/8:

A program is ill-formed if the default constructor for an object is implicitly used and the constructor is not accessible

The moment you defined Parent(int) your implicitly-defined default constructor, Parent(), is deleted.

Thus, you need to explicitly call your user-defined constructor.

Child(int v):Parent (v) { }
Joseph D.
  • 11,804
  • 3
  • 34
  • 67