views:

37

answers:

2

Consider the following:

These classes are in different header files and each header file has its corrresponding source files.

//------------------------------------------
// in Z.h

class Z
{
  public:
    Z();
    ~Z();

    void DoSomethingNasty();
}

//------------------------------------------
// in X.h
class X
{
  public:
    X();
    ~X();

    void FunctionThatCallsNastyFunctions();
}

//------------------------------------------
// in MainClass.h

#include "Z.h"
#include "X.h"

class MainClass
{
  public:
    MainClass();
    ~MainClass();

  private:
    Z _z;
    X _x;
}

And i have X.cpp:

//------------------------------------------
// in X.cpp

X::FunctionThatCallsNastyFunctions()
{

  //How can I do this? The compiler gives me error.
  _z.DoeSomethingNasty();

}

What should i do in order to call DoSomethingNasty() function from _z object? I can't figure this one out. Please help me.

Zsolt

A: 

You didn't provide the compiler error but from the sample I'm guessing the compiler error is because you only declared the DoSomethingNasty function but did not define it. This would result in an error at link time.

Try adding the following code to your .cpp file

void Z::DoSomethingNasty() {
  // Code here
}

Additionally as @Tyler pointed out, the X class does not have a member variable named _z from which to call the function on.

JaredPar
+4  A: 

The compiler is giving you an error because _z doesn't exist within the X class; it exists within the MainClass class. If you want to call a method on a Z object from X, you either need to give X its own Z object or you have to pass one to it as a parameter. Which of these is appropriate depends on what you're trying to do.

I think your confusion may be this: You think that because MainClass has both a X member and a Z member, they should be able to access each other. That's not how it works. MainClass can access both of them, but the _x and _z objects, within their member functions, have no idea about anything outside their own class.

Tyler McHenry
Thank you for your answer. I have to find another solution then.
Zsolt
You could try static methods, and you can access them with Z::DoesSomethingNasty(). You would need to pre-declare Class Z in your X file though. Or you would have to take a z object as a parameter to FuncitonThatCallsNastyFunctions.
Falmarri