S
sksjava
#include <iostream>
struct parent {
parent() : integer(0) { cout << "parent default\n"; }
parent(int i) : integer(i) { cout << "parent non-default\n"; }
int integer;
};
struct child1 : public parent {
child1() { cout << "child1 default\n"; }
child1(int i) : parent(i) { cout << "child1 non-default\n"; }
};
struct gchild : public child1 {
gchild(int i) : child1(i) { cout << "gchild non-default\n"; }
};
int main() {
gchild g(10);
cout << g.integer << endl;
}
The above code prints:
parent non-default
child1 non-default
gchild non-default
10
Modifying the line "struct child1 : public parent" to "struct child1 :
public virtual parent" will give the following result:
parent default
child1 non-default
gchild non-default
0
I am totally confused on what the compiler is doing. Thanks in advance.
struct parent {
parent() : integer(0) { cout << "parent default\n"; }
parent(int i) : integer(i) { cout << "parent non-default\n"; }
int integer;
};
struct child1 : public parent {
child1() { cout << "child1 default\n"; }
child1(int i) : parent(i) { cout << "child1 non-default\n"; }
};
struct gchild : public child1 {
gchild(int i) : child1(i) { cout << "gchild non-default\n"; }
};
int main() {
gchild g(10);
cout << g.integer << endl;
}
The above code prints:
parent non-default
child1 non-default
gchild non-default
10
Modifying the line "struct child1 : public parent" to "struct child1 :
public virtual parent" will give the following result:
parent default
child1 non-default
gchild non-default
0
I am totally confused on what the compiler is doing. Thanks in advance.