Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

inheritance and variable argument lists.

Status
Not open for further replies.

Crisps

Programmer
Sep 28, 2006
26
US
Hi,

I have a class (which I have no control of) and I would like to create a descendant of this class. The base class has functions with variable parameter lists which I would like to override. I need to then call the original function from within the overridden function.

Is this even possible?

Here is an example I wrote

Code:
#include <stdarg.h>

//The base class which I cannot chage
class A
{
protected:
	int	m_iId;
public:
	A(int iId)
	{
		m_iId = iId;
	}
	
	virtual ~A() {}

    virtual void printId(const char* szFormat, ...) const
	{
		va_list args;
		va_start(args, szFormat);

		char szBuffer[2048];

		_vsnprintf(szBuffer, sizeof(szBuffer), szFormat, args);

		printf("%d\n", m_iId);
		printf("%s\n", szBuffer);

		va_end(args);
	}
};

//This is my derived class and I have full control over this one.
class B : public A
{
public:
	B() : A(1) {}
	virtual ~B() {}

    virtual void printId(const char* szFormat, ...) const
	{
		printf("---------CLASS B HEADER------------");
		//How do I call A::printId(const char* szFormat, ...) with the arguments
		//passed to B::printId(const char* szFormat, ...)?
		
		//this obviously doesn't work
		A::printId(szFormat, ...);

		printf("---------CLASS B FOOTER------------");
	}

};

int main(int argc, char* argv[])
{
	A a(5);
	B b;

	a.printId("That was the Id for class <%s>", "A");
	b.printId("That was the Id for class <%s>", "B");

	return 0;
}
 
You don't is the short answer.

What you really need is for 'A' to provide a 'v' function (like the vsnprintf which it uses). If you have to use use varargs, then it really does make sense to provide the 'v' function to go with it, since it is basically free to implement.

Eg.
[tt]virtual void vprintId(const char* szFormat, va_list ap) const[/tt]
Then it becomes a simple matter to be able to call it from within your own code.

As it stands, the only viable option I see is to do all the work inside 'B', then do something trivial like
[tt]A::printId("%s", myBuffer);[/tt]

--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Cheers,

I may have to get changes made to the base class, esp. seeing that it is so easy.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top