lundi 28 septembre 2015

How to wrap another class (c++)

I'm trying to learn to c++ after programming in other OO languages for many years.

I'm trying to create a wrapper class for another class, but having a hard time figuring out how to set this up properly.

For instance, with the following...

main.cpp

#include "foo.cpp"
#include <iostream>

int main() {
  Foo foo(42);
  std::cout << foo.get_barx() << std::endl; 
  return 0;
}

foo.cpp

#include "bar.cpp"

class Foo {
  public:
    // I'm trying to declare the member variable `m_bar` here.  I
    //   don't want to be instantiating an instance of Bar yet,
    //   but I think that might be exactly what's happening.
    Bar m_bar;

    Foo(int y) {
      // Here's where I really want to instantiate an instance of Bar
      //   and assign it to m_bar.
      Bar m_bar(y*2);
    }   

    int get_barx() {
      return m_bar.getx();
    }   
};

bar.cpp

class Bar {
  public:
    int m_x;

    // I seem to need this default constructor for the declaration
    //   of `m_bar` above, but I don't think that line should be 
    //   calling any constructors.
    Bar() { m_x = 21; };

    Bar(int x) {
      m_x = x;
    }   

    int getx() {
      return m_x;
    }   
};

When I compile and run this, I get back 21, but I expect 84. I'm pretty sure I'm doing something fundamentally wrong, and I'm pretty sure it's got something to do with how I'm declaring the m_bar member variable in Foo, but I can't figure out what the right way is to accomplish this.

Aucun commentaire:

Enregistrer un commentaire