Search code examples
c++objectconstructorencapsulation

c++ objects with constructors taking values into encapsulated objects


I have been trying to figure out how c++ handles multiple objects, with constructors that take in values, that are set up inside of each other.

#include <iostream>
using namespace std;

class Inner {
  int myvar;
public:
  Inner(int input) {
    myvar = input;
  }

  int output() {
    return myvar;
  }
};

class Outer {
  Inner inner;
public:
  Outer(int input) {
    Inner inner(input);
  }

  int value_out() {
    return inner.output();
  }
};

int main() {
  int myvar = 0;
  Outer outer(myvar);
  cout << outer.value_out() << endl;
  return 0;
}

My console output when I go to compile:

ubuntu@ubuntu:~$ cd Desktop
ubuntu@ubuntu:~/Desktop$ touch test.cpp
ubuntu@ubuntu:~/Desktop$ g++ test.cpp -o test
test.cpp: In constructor ‘Outer::Outer(int)’:
test.cpp:19:20: error: no matching function for call to ‘Inner::Inner()’
   Outer(int input) {
                    ^
test.cpp:19:20: note: candidates are:
test.cpp:7:3: note: Inner::Inner(int)
   Inner(int input) {
   ^
test.cpp:7:3: note:   candidate expects 1 argument, 0 provided
test.cpp:4:7: note: Inner::Inner(const Inner&)
 class Inner {
       ^
test.cpp:4:7: note:   candidate expects 1 argument, 0 provided
ubuntu@ubuntu:~/Desktop$ 

I am new to c++ so just looking for better understanding on how everything falls into place. I am coming from scripting languages like python and ruby where a lot of this is done automatically. Thank you for help!

Here is what I am trying to do working in Ruby if this helps to better make it clear what I am trying to do here....

class Inner
  def initialize(input)
    @myvar = input
  end

  def output
    @myvar
  end
end

class Outer
  def initialize(input)
    @inner = Inner.new(input)
  end

  def value_out
    @inner.output
  end
end

myvar = 0
outer = Outer.new(0)
puts outer.value_out

So I guess the core of my question is How do i write an object, that has a default constructor as a member variable of another object since c++ freaks out if I assign anything to a member variable. So how does one input anything inside an object that requires an input if its a member variable of another object? Is this even possible or am I trying to do something that is incredibly stupid and bad?


Solution

  • I think you are a little confused about the member variable inner and the inner used in the constructor body

    In your constructor body,

    Outer(int input) {
      Inner inner(input);
    }
    

    The variable inner is not the class member. It is a local variable in the scope of the function. To initialize the class member, you will need to use:

    Outer(int input) : inner(input) {}