Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

c++ - Override initial value of a member variable of base class

I am very confused with the inheritance right now. I planned to simply override the initial value of a variable. In the following code i just inherit the base class and try to get it's name, which is saved as a string withing the class. I expected that the derived class can override this value, however it does not do it.

My expected out put was

Derived
Derived

However i get

Base
Base

What is the correct way to implement the following?

#include <iostream>
#include <string>

struct Base {
    virtual ~Base() = default;
    virtual void id(){
        std::cout << id_ << std::endl;
    }
    std::string id_ = "Base";
};   



struct Derived : public Base {
    virtual ~Derived() = default;
    std::string id_ = "Derived";
};   


int main(){
    Base* b = new Derived();
    Derived* d = new Derived();
    b->id();
    d->id();
    delete d;
    delete b;                                                                                                          
    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What is the correct way to implement the following?

Without meaning to sound difficult, it really depends on exactly what you want to achieve.

I'm going to make a guess that we're simply be asking an object what type it is, regardless of which interface we're calling on:

struct Base {
  virtual ~Base() = default;

  virtual const std::string id() const {
    return "Base";
  }
};

struct Derived : Base {
  virtual const std::string id() const override {
    return "Derived";
  }
};

Here's another way:

struct Base {
  virtual Base(std::string ident = "Base") 
  : _id(std::move(ident))
  {}

  virtual ~Base() = default;

  std::string& id() const {
    return _id;
  }

private:
  std::string _id;

};

struct Derived : Base {
  Derived() : Base("Derived") {}
};

And another, using value is interface, but note that this will disable the assignment operator

struct Base {
  virtual Base(std::string ident = "Base") 
  : id(std::move(ident))
  {}

  virtual ~Base() = default;

  const std::string id;

};

struct Derived : Base {
  Derived() : Base("Derived") {}
};

This list is by no means exhaustive.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...