Static Inheritance

I want each class to have its own static code, which can be requested from each object. I think about it, but it doesn't seem to work:

#include <iostream>

class Parent {
protected:
    static int code;
public:
    int getCode();
};

int Parent::code = 10;
int Parent::getCode() {
  return code;
}

class Child : public Parent {
protected:
    static int code;
};

int Child::code = 20;

int main() {
  Child c;
  Parent p;

  std::cout << c.getCode() << "\n";
  std::cout << p.getCode() << "\n";

  return 0;
}

It outputs:

10

10

while waiting

twenty

10

+4
source share
4 answers

You must make the getCode () function "virtual" and must implement the following codes each time:

class Parent {
protected:
    static int code;
public:
    virtual int getCode() { return code; }
};

int Parent::code = 10;

class Child : public Parent {
protected:
    static int code;
public:
    virtual int getCode() { return code; }
};

int Child::code = 20;

int main() 
{
    Child c;
    Parent p;

    std::cout << c.getCode() << "\n";
    std::cout << p.getCode() << "\n";
    return 0;
}
+1
source
class Parent {
public:
    virtual int getCode();

    // Looks like a variable, but actually calls the virtual getCode method.
    // declspec(property) is available on several, but not all, compilers.
    __declspec(property(get = getCode)) int code;
};


class Child : public Parent {
public:
    virtual int getCode();
};

int Parent::getCode() { return 10; }
int Child::getCode()  { return 20; }

int main() {
  Child c;
  Parent p;

  std::cout << c.code << "\n"; // Result is 20
  std::cout << p.code << "\n"; // Result is 10

  return 0;
}
+1
source

-?

class Parent {
public:
    static int getCode();
};

int Parent::getCode() {
  return 10;
}

class Child : public Parent {
public:
    static int getCode();
};

int Child::getCode() {
  return 20;
}

- . .

0

:

In the parent class, you do not declare your getCode function virtual. That way, whenever you call it with a class that inherits from your parent class, it just returns the int code from the parent class.

To fix this:

  • First declare the getCode function virtual in your parent class.
  • Second, write another getCode function in the inherited class and return the int code from the inherited class
0
source

All Articles