-3

I have a class first in which I want to have another element that its type is another class. Something like this:

class first{

private:

    second secondAvl;
public:

    first():second(-1){}  // i get erroe here
} 

class second: public Tree{

private:

public:
 second(int key) :Tree(NULL,key1){} // here it worked to call contructor for tree
}

My problem is that when I try to call the constructor for second in class first constructor I get this error:

no matching function for call to 'second::second()'

Any help what I am doing wrong? Because I did the same thing when I called the constructor for tree in the second class and that worked fine.

DeiDei
  • 10,205
  • 6
  • 55
  • 80
user7886490
  • 115
  • 1
  • 1
  • 5
  • You need to name the member, not the member's type. `first() : secondAvl(-1) {}` Consider what would happen if you have two `second` members. You only name the type when you call a base type's constructor. And remember that `second` must be declared before being used in `first`. – François Andrieux May 15 '18 at 18:00
  • 1
    `first():second(-1){}` This says: "When default-constructing a `first`, initialize my member named `second` by calling its constructor with a value of `-1`." You don't have a member named `second`, so this fails. – 0x5453 May 15 '18 at 18:02
  • dublicate: [https://stackoverflow.com/questions/41534186/c-calling-another-class-constructor] – Michał Kalinowski May 15 '18 at 18:06
  • The code provided could not trigger the error reported. – SergeyA May 15 '18 at 18:14

2 Answers2

1

First, in the order you define the classes, class second is not known at the time it is used in first. You should actually get other error messages. Second, in the initializer list, you need to address the variable to initialize by its name (i.e. : secondAvl(-1)), not by its type : second(-1).

See the following working example:

class second {

private:

public:
    second(int key) {} // here it worked to call contructor for tree
};


class first{

private:

    second secondAvl;
public:

    first():secondAvl(-1){}  // i get erroe here
};
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
-1

do instead:

...

private:

    second secondAvl;
public:

    first() : secondAvl(-1)
    { }  
}

or uniform initialization using {}

...

private:

    second secondAvl;
public:

    first() : secondAvl{-1}
    { }  
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97