Advertisement
Guest User

Untitled

a guest
Feb 20th, 2020
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. /* main.cpp */
  2. #include "A.hpp"
  3. #include "B.hpp"
  4. #include <iostream>
  5.  
  6. int main() {
  7.     A a(10);
  8.     std::cout << a.GetValue(0) << "\n"; // invokes B::GetValue
  9.  
  10.     B b(0);
  11.     b.GetMessage(); // invokes A::Print
  12.  
  13.     return 0;
  14. }
  15. /* !main.cpp */
  16.  
  17. /* a.hpp */
  18. #pragma once
  19. #include <vector>
  20.  
  21. class B;
  22. class A {
  23.     public:
  24.         A(std::size_t size);
  25.         ~A();
  26.        
  27.         static void Print();
  28.         int GetValue(std::size_t index);
  29.  
  30.     private:
  31.         std::vector<B*> m_Population;
  32. };
  33. /* !a.hpp */
  34. /* a.cpp */
  35. #include "A.hpp"
  36. #include "B.hpp"
  37. #include <iostream>
  38. #include <stdexcept>
  39.  
  40. A::A(std::size_t size) {
  41.             m_Population.reserve(size);
  42.             for (std::size_t i = 0; i < size; i++)
  43.                 m_Population.emplace_back(new B(i));
  44.         }
  45.  
  46. A::~A() {
  47.     for (auto& ptr : m_Population) {
  48.         delete ptr;
  49.         ptr = nullptr;
  50.     }
  51. }
  52.  
  53. int A::GetValue(std::size_t index) {
  54.     if (index >= m_Population.size())
  55.         throw std::out_of_range("Invalid index!");
  56.  
  57.     return m_Population[index]->GetValue();
  58. }
  59.  
  60. void A::Print() {
  61.     std::cout << "Hello World!\n";          
  62. }
  63. /* !a.cpp */
  64.  
  65. /* b.hpp */
  66. #pragma once
  67.  
  68. class A;
  69.  
  70. class B {
  71.     public:
  72.         B(int a);
  73.         ~B();
  74.  
  75.         void GetMessage();
  76.         int GetValue() const;
  77.  
  78.     private:
  79.         int m_Val;
  80. };
  81. /* !b.hpp */
  82. /* b.cpp */
  83. #include "B.hpp"
  84. #include "A.hpp"
  85.  
  86. B::B(int val) : m_Val(val) {}
  87. B::~B() {}
  88.  
  89. void B::GetMessage() {
  90.     A::Print();
  91. }
  92.  
  93. int B::GetValue() const {
  94.     return m_Val;
  95. }
  96. /* !b.cpp */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement