Question:
How do I make two C++ classes interact?
BlabberBlab
2007-12-25 16:50:04 UTC
Hello.

I have two classes, which I want to interact.

class Demo
{
public:
bool init(HWND);

protected:
LPDIRECT3D9 d3d;
LPDIRECT3DDEVICE9 d3ddev;
};

class Render
{
public:
void render();
};

--

Basically, I want Render to have access to the protected objects in D3D. I am trying to come up with a clean way to structurize my code, but I am lost at this.

I was thinking of somehow passing a reference to my D3D object to the Render-constructor, but I just got a bunch of compiler-errors when trying that.

Hope someone can help me out :)
Three answers:
2007-12-25 17:30:54 UTC
I am not much a graphics guy so I don't know off-hand where you ultimately want to go with this. But that said,



(1) The demo class seems basically useless. It seems properly like you want to rename it something like a Device class. Keep your variables protected (or more likely private unless there is some reason who haven't specified for them being protected) and create some public methods which use those variables.



(2) Again, being graphics ignorant, is render something that belongs to the Device, or a subclass of Device, or is it truly independent of the device? If it really is independent then passing the Device into a Render object is an ok way to go. But honestly, just on instinct, it seems that Render is something that a device *does*, not something that is independent.



So off the top of my head:



(1) set up a Device interface



class BaseDevice

{

public:

BaseDevice();

virtual ~BaseDevice();



virtual void doSomething() = 0;

virtual void doOtherThing() = 0;

virtual void render() = 0;

}



(2) Make a concrete Device class.



class Device : public BaseDevice

{

public:

Device();

virtual ~Device();



virtual void doSomething();

virtual void doOtherThing();

virtual void render();



private:



LPDIRECT3D9 d3d;

LPDIRECT3DDEVICE9 d3ddev;

}



void Device::render()

{

d3d.paintFancyStuff();

}





Basically I think you need to think your class hierarchy out more carefully. As a general rule your classes are going to be nouns, not verbs. Group common functionality of a class hierarchy into an interface and then have concrete classes implement the functionality.
angmar248
2007-12-25 17:15:11 UTC
To let Render have access to the protected objects in D3D/Demo you need to either have accessor functions (setter and getter functions) or make Render a friend. Personally I don't like using the friend method but I'm sure others will disagree with me.

I don't see a constructor here to allow you to pass a D3D object to a Render constructor. Did you have one in there when you got your compile errors? If so, what were the errors?

Singletons are fairly simple but don't use them unless you need to.
Generoushous
2007-12-25 23:16:24 UTC
use friend classes !


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...