-3

I am new to C++ programming and I need your help:

Let's say I have a class - Class1. Is it possible to have another class (Class2) with (at least) one function that returns (for example) an integer? Here is an example with I want to achive:

std::cout << "I did it: " << Class1.Class2.ReturnINTEGER() << std::endl;

I need the code to be compatible with GNU G++ compiler. Thanks :).

2 Answers2

1
#include <iostream>
using namespace std;
class Two
{
public:
    int toReturn;
    Two()
    {
        toReturn=0;
    }

    int returnValue() 
    {
         return toReturn;
    } 
};

class One
{
 public:
     Two foo;
};

int main() 
{
    One bar;
    int toPrint=bar.foo.returnValue();
    cout << toPrint << endl;
} 
Seth Kitchen
  • 1,526
  • 19
  • 53
  • Ok - i tried to solve the errors - here: – VVI C And C 15 Sep 20 '16 at 19:27
  • #include using namespace std; class Two { public: int toReturn; Two() { toReturn=0; } int returnValue() { return toReturn; } }; class One { public: Two foo; }; int main() { One bar; int toPrint=bar.foo.returnValue(); cout << toPrint << endl; } – VVI C And C 15 Sep 20 '16 at 19:27
0

Yes, it can be done. Let's dissect or rebuild. First to get Class1.Class2, we need to have a class member called Class2. And Class2 needs to have a member called Fct.

Here is one implementation:

struct Class2_Object
{
  void Fct(void);
};

struct Class1_Object
{
  Class2_Object Class2;
};

Class1_Object Class1;
Class1.Class2.Fct();
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154