0

C++

#include <stdio.h>

class a
{ 
    public: 
        int var1; 
        a(int var) 
        {
            var1 = var; 
            printf("set var1 to %d\n", var1);
        } 
}; 
class b: public a 
{ 
    public: 
        int var2; 
        b(int d) : var2(d++), a(var2++)
        {
            printf("d: %d, var2: %d, var1: %d\n", d, var2, var1);
        } 
}; 

int main()
{ 
    int a = 5;
    b obj1(a);  
    printf("%d\n", obj1.var1);
} 

Output:

set var1 to 0
d: 6, var2: 5, var1: 0
0
[Finished in 0.7s]

Why is a.var1 not set to 6 here?

1
  • 2
    Using a as an int variable when you also have a public class named a obscures the code a bit, although isn't the cause of your problem. Commented May 26, 2013 at 17:21

1 Answer 1

4

Because C++ ignores the order in which you list the member initializations. The base-class ctor is always called before other members are initialized.*

So I believe you're invoking undefined behaviour here; you're passing var2 as the ctor argument, but it's not yet initialized.


* The compiler should warn you about this, if you allow it. For example, compiling your code with GCC with the -Wall flag gives the following message:

test.cc: In constructor "b::b(int)":
test.cc:16: error: "b::var2" will be initialized after
test.cc:17: error:   base "a"
test.cc:17: error:   when initialized here

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.