Retaining *this in method chaining

A

Ashwin Nanjappa

Hi folks,

I've got a class setup as shown below:

class A
{
public:
A& call()
{ return *this; }

void init()
{ }
};

class B : public A
{
public:
void init()
{ }
};

B b;
b.call().init();

This calls class A's init instead of that of B. This is because call()
returned object of type A instead of B. Is there any other way to
design these classes so that functions like call() know how to return
their actual object instead of the base object?

Why do I want this crazy setup? I want to retain the ability to do
method chaining (b.call1().call2().call3() ...) But, doing it on
inherited classes complicates matters like this :-(

Rgds,
~ash
 
R

Rolf Magnus

Ashwin said:
Hi folks,

I've got a class setup as shown below:

class A
{
public:
A& call()
{ return *this; }

void init()
{ }
};

class B : public A
{
public:
void init()
{ }
};

B b;
b.call().init();

This calls class A's init instead of that of B.

B doesn't even have its own implementation.
This is because call() returned object of type A instead of B. Is there
any other way to design these classes so that functions like call() know
how to return their actual object instead of the base object?

Yes. Make A::call() virtual. If your text book doesn't describe how to use
polymorphism in C++, throw it away, because that's a basic language
feature.
 
A

Ashwin Nanjappa

Yes. Make A::call() virtual. If your text book doesn't describe how to use
polymorphism in C++, throw it away, because that's a basic language
feature.

Thanks, this is exactly what I was looking for.

Regards,
~ash
 
R

Rossonera

Hi,
I think there are two ways to resolve your problem.
1. add B& call() {} member function.
2. declare void init() as virtual in class A.
both of them can resolve your problem.
 
A

Ashwin Nanjappa

Hi,
I think there are two ways to resolve your problem.
1. add B& call() {} member function.
2. declare void init() as virtual in class A.
both of them can resolve your problem.

Yes, this is why I was a bit confused. Solution 2 works for me. This
is because this particular class(es) have a lot of methods that can be
chained but only one init call.

~ash
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top