I'm having trouble trying to call the super constructor in C++ from a derived class. There are two different cases:
1. As you may know, the way to do this in Java is by using super keyword in the constructor of the child class, I guess I'm making a mistake because even though my C++ code does print the Hello World statement, it prints it twice.
Here are the two codes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//Java
class A{
public A(){
System.out.println("Hello world!");
}
}
class B extends A {
public B(){
super();
}
}
class Main{
publicstaticvoid main(String args[]){
new B();
}
}
//C++
#include <iostream>
usingnamespace std;
struct Super{
Super(){
cout << "Hello world" <<endl;
}
};
struct Sub : public Super{
Sub(){
Super();
}
};
int main(){
Sub sub;
}
2. The second case is about values passed as parameters. Again, it works in Java but not in C++. I'm obviously doing something wrong in C++ in both situations, can anybody help me out? thanks a lot.
//Java
class A{
int x;
public A(int x){
this.x = x;
System.out.println("Value: " + 5);
}
}
class B extends A {
public B(){
super(5);
}
}
class Main{
publicstaticvoid main(String args[]){
new B();
}
}
#include <iostream>
usingnamespace std;
struct Super{
Super(){
cout << "Hello world\n";
}
};
struct Sub : public Super{
};
int main(){
Sub sub;
}
(you could of course write an empty constructor for Sub, somthing like Sub() {} or even Sub() : Super() {}, but that's exactly what the compiler does in this case, so there's no reason to)
Second:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
struct Super{
int x;
Super(int x) : x(x) {
cout << "Value: " << x << '\n';
}
};
struct Sub : public Super{
Sub() : Super(5) {
}
};
int main(){
Sub sub;
}
Remember, in C++ a class is not limited to having just one parent, so there is no special word for *the* parent. Just use the name of the particular base class you want to initialize in the constructor.