Attribute Setting Methods

K

kjell

Hi,

I wonder if someone may have a solution to a small problem I'm
experiencing with a C++ program? I'm have two classes in my
application that provides methods for setting parameters in the
classes. These methods returns a pointer to the class itself so that
you can use the return value to call another attribute setting method
on the same line. This is what my program look like:

#include <iostream>



using namespace std;



class CBase

{

public:

CBase* SetParameterA(const int nA)

{

m_nA = nA;

return this;

};



private:

int m_nA;

};




class CSub: public CBase

{

public:

CSub* SetParameterB(const int nB)

{

m_nB = nB;

return this;

};



private:

int m_nB;

};




main()

{

CSub* pMyInstance = new CSub();

pMyInstance->SetParameterB(1)->SetParameterA(2);

delete pMyInstance;

}


The problem is that if I call SetParameterA() before SetParameterB()
I get a compiler error. I change the third line from the end to:

pMyInstance->SetParameterA(2)->SetParameterB(1);


When I compile the program I get the following error:

> g++ test.cc

test.cc: In function 'int main()':

test.cc:37: error: 'class CBase' has no member named 'SetParameterB'


This is because SetParameterA() returns a pointer to CBase and CBase
does not have a method SetParameterB().

So I'm trying to find a solution to this problem.

One thing that I could do is make the method SetParameterA()
polymorphic, override it in CSub, call the SetParameterA() method in
base class and then type cast the return pointer. The problem with
this approach is that I would have to write wrappers for all methods
in the base class CBase in the derived class CSub.

Would you by any chance have a more elegant solution to this problem?

Thanks for you help,
Kjell
 
A

Al Balmer

I wonder if someone may have a solution to a small problem I'm
experiencing with a C++ program?

You're more likely to get useful answers in comp.lang.c++.
 
M

Martin Ambuhl

Hi,

I wonder if someone may have a solution to a small problem I'm
experiencing with a C++ program?

Someone in <might. The _first_ thing to learn is
that C and C++ are different languages.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top