Flexo1515
Flexo1515

Reputation: 1017

C++ constructor calling another constructor

When attempting to build a c++ program containing the following code:

menutype::menutype(int cat_num){
    extras list = extras(cat_num);
}

extras::extras(int num_cats){
    head = new category_node;
    head->next = NULL;
    head->category = 1;
    category_node * temp;
    for(int i = 1; i < (num_cats); ++i){
        temp = new category_node;
        temp->next = head->next;
        head->next = temp;
        temp->category = (num_cats-(i-1));
    }
}

I receive the error :

cs163hw1.cpp: In constructor ‘menutype::menutype(int)’:
cs163hw1.cpp:59:31: error: no matching function for call to ‘extras::extras()’
cs163hw1.cpp:59:31: note: candidates are:
cs163hw1.cpp:5:1: note: extras::extras(int)

And I do not understand why, please help!

Upvotes: 1

Views: 360

Answers (4)

bobestm
bobestm

Reputation: 1334

One would typically call a constructor within a constructor of another class (as in your example) the following way:

menutype::menutype(int cat_num) : list(cat_num) { }

This is more efficient as the constructor for list (of type extra) is called in the initialiser list.

Upvotes: 1

Geoff Montee
Geoff Montee

Reputation: 2597

As others said, you are calling the constructor incorrectly.

Three other people have already pointed out the proper initializer list method. However, no one has pointed out how to properly call a constructor outside of a constructor context.

Instead of:

extras list = extras(cat_num);

Do:

extras list(cat_num);

Upvotes: 1

It seems like your menutype holds a member of type extras. If that is the case, and if extras does not have a default constructor (as it seems to be the case) you need to initialize it in the initialization list:

menutype::menutype(int cat_num) : myextrasmember(cat_num) {}

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258648

Since that line shouldn't attempt to call a default constructor (only copy constructor and conversion constructor from int), I'll just guess that you have a data member of type extras in your class menutype, so you have to initialize it in the initializer list because it doesn't have a default constructor:

menutype::menutype(int cat_num) : list(cat_num) { //or whatever the member is called

}

Upvotes: 5

Related Questions