1

With the following code I want accomplish two different values for intA, but I get:

clsA a=1? 1 clsB a=2? 1

//Code
#include <iostream>
using namespace std;
class clsA {
    static const int intA = 1; 
public:
    virtual int get_a() { return intA; }
};
class clsB: public clsA { 
    static const int intA = 2;   
}; 
int main() { 
    clsA a; clsB b;
    cout << "clsA intA =  " << a.get_a() << endl;
    cout << "clsB intA =  " << b.get_a() << endl;
}

How can I get intA=1 for object a and intA=2 for object b? Thanks for the reaction, André

2
  • What you are looking for is late static binding. It has been a while since I last did c++. I do not remember if it supports late static binding. Commented Mar 17, 2012 at 20:06
  • Actually I want clsA::intA=5 and clsB::intA=8. I have two intA s for the rest of the code, clsA delivers 5 random numbers and clsB delivers 8 random numbers Commented Mar 17, 2012 at 20:17

4 Answers 4

1

Try this:

class clsB: public clsA {
    static const int intA = 2;
public:
    virtual int get_a() { return intA; }
};

The reason the other didn't work is that there literally existed no method clsB::get_a(). There only existed a vtable entry to which such a method might have been attached. The above attaches the method.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to tell the compiler that when get_a is called on clsB, it needs to return the intA defined in that same class:

class clsB: public clsA { 
    static const int intA = 2;   
    virtual int get_a() { return intA; }
};

However, this way of orchestrating things is not the best perhaps. Given that the allure of "automatically getting the correct value" is diminished by the fact that it's impossible to do that, giving the constants different names might be a good idea.

Comments

1

You are still calling the base function which can only see the bases version of a.

class clsA {
    static const int intA = 1; 
public:
    virtual int get_a() { return intA; }
};
class clsB: public clsA { 
    static const int intA = 2;   
    int get_a() { return intA; }
}; 

int main() { 
    clsA a; clsB b;
    cout << "clsA intA =  " << a.get_a() << endl;
    cout << "clsB intA =  " << b.get_a() << endl;
}

Comments

0

Add an implementation of get_a() to clsB:

class clsB: public clsA { 
    static const int intA = 2; 
public:
    virtual int get_a() { return intA; }
}; 

However, it's confusing to have two different values for intA. I suggest a different naming scheme, such as intB in clsB.

2 Comments

What he is trying to do is to overload the static variable. It is not really that confusing.
@d_inevitable: I suggest that is confusing, because C++ doesn't have the concept of "overloading a static variable". That's pretty much the opposite of what static means.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.