I want to practice C++ by coding a simple mobile phone application with an interchangeable system. I created a System base class and also created MyOS class which extends the System class. In the Phone class, I have a variable of System class because I think like in Java, you can assign it with child class. (eg. System sys = new MyOS();). But in C++ it calls the function in the base class.
What I want to work in C++ but it's in Java.
public class MyParent {
public void start() {
System.out.println("start() executed in MyParent");
}
}
public class MyChild extends MyParent {
@Override
public void start() {
System.out.println("start() excecuted in MyChild");
}
}
public class Inherit {
MyParent parent;
public Inherit(MyParent parent) {
this.parent = parent;
}
public void start() {
parent.start();
}
}
public class TestInherit {
public static void main(String[] args) {
Inherit i = new Inherit(new MyChild());
i.start();
}
}
Output: start() excecuted in MyChild
My current c++ code:
System.h
#pragma once
#include <iostream>
class System {
public:
void start() {
std::cout << "Booting System..." << std::endl;
}
};
MyOS.h
#pragma once
#include <iostream>
#include "System.h"
class MyOS: public System {
public:
// Override
void start() {
std::cout << "Booting MyOS..." << std::endl;
}
};
Phone.h
#pragma once
#include "System.h"
class Phone {
public:
Phone(System system) {
Phone::system = system;
}
void start() {
system.start();
}
private:
System system;
};
MyPhone.cpp
#include "MyOS.h"
#include "Phone.h"
#include "System.h"
int main() {
MyOS os;
Phone myPhone(os);
myPhone.start();
return 0;
}
Output: Booting System...