Travis Su Travis Su - 1 month ago 6x
C++ Question

How to call function from a two-level inherited class in C++?

I got a main program in prog2.cpp

#include "stack1.h"
int main(void){
stack1 x(100); // Declare a stack1 x of length 100

And I need to call this stack1 from stack1.h, but this original function is from stack.h, with is a parent class of stack1.h:

class stack
stack(int length);

stack1.h is now looking like this:

#include "stack.h"
class stack1: public stack{
...... //irrelevant code

Problem is stack1 x(100) got an error from MVS saying:

Error: no instance of constructor "stack1::stack1" matches the argument list.

I've tried many ways to get rid of this but it always led to more problems. How do I fix this?


It is the subclass's constructor's responsibility to invoke the superclass's constructor.

You need to declare a constructor in the stack1 class that, basically, forwards its parameter to its superclass's constructor:

struct stack1: public stack {

   stack1(int n) : stack(n) {}


You're not really calling a function here. You're calling a constructor. The rules for constructors are different. Normally, there's no issue with using a subclass to invoke a method that's inherited from a superclass. This is straightforward. But in this case, it's not really a method, it's a constructor. Different rules apply.