Struct Embedding in C++
#include <iostream>
#include <string>
#include <memory>
class Base {
protected:
int num;
public:
Base(int n) : num(n) {}
std::string describe() const {
return "base with num=" + std::to_string(num);
}
};
class Container : public Base {
private:
std::string str;
public:
Container(int n, const std::string& s) : Base(n), str(s) {}
const std::string& getStr() const { return str; }
};
class Describer {
public:
virtual std::string describe() const = 0;
virtual ~Describer() = default;
};
int main() {
Container co(1, "some name");
// We can access the base's fields directly on co
std::cout << "co={num: " << co.describe().substr(14) << ", str: " << co.getStr() << "}\n";
// We can also access the base's methods
std::cout << "describe: " << co.describe() << "\n";
// Demonstrate polymorphism using the Describer interface
std::unique_ptr<Describer> d = std::make_unique<Container>(co);
std::cout << "describer: " << d->describe() << "\n";
return 0;
}
C++ supports inheritance which is similar to struct embedding in Go. In this example, we’ve translated the concept of struct embedding to class inheritance in C++.
The Base
class corresponds to the base
struct in Go. It has a num
field and a describe
method.
The Container
class inherits from Base
, which is similar to embedding in Go. It adds an additional str
field.
We’ve also created a Describer
interface to demonstrate polymorphism, which is similar to how Go interfaces work.
In the main
function, we create a Container
object and demonstrate how we can access both the inherited members from Base
and the members specific to Container
.
To compile and run this program:
$ g++ -std=c++14 struct_embedding.cpp -o struct_embedding
$ ./struct_embedding
co={num: 1, str: some name}
describe: base with num=1
describer: base with num=1
This example demonstrates how C++ uses inheritance to achieve a similar effect to Go’s struct embedding. It allows for code reuse and enables polymorphism through inheritance and virtual functions.