1

This is kinda multiple questions in a single question. First off, is there a way to initialize inherited values in C++? In other words, this is what I mean in java :

// Class X
public class X {
    int num;
    public X(int num) {
        this.num = num;
    }
}

//Class Y
public class Y extends X{

    public Y() {
        super(5);
    }
}

My other question is how would I create an abstract method in C++? Again, java example :

// Class x
public abstract class X {
    int num;
    public X(int num) {
        this.num = num;
    }
    public abstract void use();
}
// Class y
public class Y extends X{

    public Y() {
        super(5);
    }

    @Override
    public void use() {

    }
}

Thanks.

Bob Joe
  • 27
  • 1
  • 6

1 Answers1

2

First: You want to learn about initializer lists. For your first code snippet, the appropriate code would be

class X {
    int num;
public:
    X(int t_num) : num(t_num) { } // We can use initializer lists to set member variables
};

class Y : public X {
public:
    Y() : X(5) { } // No need to have anything in the body of the constructor
};

For the second, in C++ you can always declare functions without providing a definition, which is very similar to defining an abstract function in Java. If your intent is to do run-time polymorphism, you'll also want to make them virtual functions:

class X {
    int num;
public:
    virtual void use() = 0; // The = 0 indicates there's no implementation in X
};

class Y : public X {
    void use() override { } // No need to redeclare virtual
                            // override keyword not necessary but can be clarifying
};
Nathan Pierson
  • 5,461
  • 1
  • 12
  • 30
  • You need `virtual void use() = 0;` to make `X` an abstract class, which achieves the same goal as in Java. See https://stackoverflow.com/a/2652223/2089675 – smac89 Oct 07 '20 at 00:01
  • The second example makes sense, but for the first example, could you show that the x class/struct is? – Bob Joe Oct 07 '20 at 00:09