Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* main.cpp */
- #include "A.hpp"
- #include "B.hpp"
- #include <iostream>
- int main() {
- A a(10);
- std::cout << a.GetValue(0) << "\n"; // invokes B::GetValue
- B b(0);
- b.GetMessage(); // invokes A::Print
- return 0;
- }
- /* !main.cpp */
- /* a.hpp */
- #pragma once
- #include <vector>
- class B;
- class A {
- public:
- A(std::size_t size);
- ~A();
- static void Print();
- int GetValue(std::size_t index);
- private:
- std::vector<B*> m_Population;
- };
- /* !a.hpp */
- /* a.cpp */
- #include "A.hpp"
- #include "B.hpp"
- #include <iostream>
- #include <stdexcept>
- A::A(std::size_t size) {
- m_Population.reserve(size);
- for (std::size_t i = 0; i < size; i++)
- m_Population.emplace_back(new B(i));
- }
- A::~A() {
- for (auto& ptr : m_Population) {
- delete ptr;
- ptr = nullptr;
- }
- }
- int A::GetValue(std::size_t index) {
- if (index >= m_Population.size())
- throw std::out_of_range("Invalid index!");
- return m_Population[index]->GetValue();
- }
- void A::Print() {
- std::cout << "Hello World!\n";
- }
- /* !a.cpp */
- /* b.hpp */
- #pragma once
- class A;
- class B {
- public:
- B(int a);
- ~B();
- void GetMessage();
- int GetValue() const;
- private:
- int m_Val;
- };
- /* !b.hpp */
- /* b.cpp */
- #include "B.hpp"
- #include "A.hpp"
- B::B(int val) : m_Val(val) {}
- B::~B() {}
- void B::GetMessage() {
- A::Print();
- }
- int B::GetValue() const {
- return m_Val;
- }
- /* !b.cpp */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement