Recommended Posts

Hello
i am working on a project and want to know if you can call a member function In another member function of the same. And if you can do call it with the class name as a prefix with the double colons?

Share this post

Link to post

Share on other sites

While alvaro's point is certainly valid, sometimes code that compiles, runs and appears correct isn't in fact correct.

i am working on a project and want to know if you can call a member function In another member function of the same.
[/quote]
You trailed off your question at an important point, "of the same..." - the same what? Class? Yes, you can call member functions from other member functions inside the same class.

And if you can do call it with the class name as a prefix with the double colons?
[/quote]
Yes. I wouldn't recommend it though:

It is verbose

It means that if you change your class name you'll have to fix up any place you've used the class name

Let us now imagine that the code is evolving, and we need Example to become an abstract class. It should have a default implementation of foo(), but no implementation of ba() - i.e. foo will be virtual and bar will be pure virtual.

class Example
{
public:
virtual ~Example()
{
}

virtual void foo()
{
std::cout << "Foo called!\n";
}

virtual void bar() = 0;
};

Let us not focus on whether this design is a good idea, just that it is possible.

Now, imagine we need to have a concrete implementation that behaves like the original. Something like the following:
class DefaultExample : public Example
{
public:

If we simply write a call to foo(), then if DefaultExample, or a child class thereof, overrides foo() at some later point, the most derived implementation will be called. Alternatively, if Example::foo() is written, then regardless of whether we override foo in DefaultExample or some child class, only the parent implementation will be called.

By explicitly using the class name, we change the behaviour of the program.

This is one example of inheritance introducing strong coupling, and why composition is favoured over inheritance, why shallow inheritance hierarchies are preferred and why base classes with no behaviour reduce coupling.