Jump to content

Welcome to Geeks to Go - Register now for FREE

Geeks To Go is a helpful hub, where thousands of volunteer geeks quickly serve friendly answers and support. Check out the forums and get free advice from the experts. Register now to gain access to all of our features, it's FREE and only takes one minute. Once registered and logged in, you will be able to create topics, post replies to existing threads, give reputation to your fellow members, get your own private messenger, post status updates, manage your profile and so much more.

Create Account How it Works
Photo

C++ Inheritance


  • Please log in to reply

#1
W-Unit

W-Unit

    Member

  • Member
  • PipPipPip
  • 170 posts
Alright, so I have a pure abstract class, Jar, with a few protected methods (nextMarble, hasMarble, and resetIteration) that need to be overridden in inheriting class VectorJar.

A different, public method in VectorJar (merge) will then need to call these methods.

Jar.cpp
class Jar
{
public:
        // ...
protected:
	struct MarbleIterationException { };

	virtual Marble nextMarble() const = 0;
	virtual bool hasMarble() const = 0;
	virtual void resetIteration() const = 0;
};

VectorJar.cpp
class VectorJar : Jar
{
	int iterIndex;
	rcvector<Marble> marbles;
	
	// ...

protected:
	Marble nextMarble() const
	{
		if (iterIndex < marbles.size())
			return marbles[iterIndex++];

		else
			throw MarbleIterationException();
	}

	bool hasMarble() const
	{
		return (iterIndex < marbles.size());
	}

	void resetIteration() const
	{
		iterIndex = 0;
	}

	// ...

public:
	void merge(const Jar& jar1, const Jar& jar2)
	{
		clear();

		if (jar1.marble_number() < jar2.marble_number()) return merge(jar2,jar1);

		jar1.resetIteration();
		while (jar1.hasMarble())
		{
			Marble m1 = jar1.nextMarble();
			jar2.resetIteration();
			while (jar2.hasMarble())
			{
				Marble m2 = jar2.nextMarble();
				if (m1 == m2) add(m1);
			}
		}

		jar1.resetIteration();
		jar2.resetIteration();
	}
};

The problem I am having is that the compiler won't let me call the nextMarble, resetIteration, and hasMarble methods from within the merge method. The compiler says it "cannot access private member declared in class Jar."
If I change the first line of VectorJar.cpp from class VectorJar : Jar to class VectorJar : public Jar, then the error changes so to "cannot access protected member declared in class Jar."
Since VectorJar inherits from Jar, it should be able to access Jar's protected methods, right? Otherwise, what is the point of a protected method?

Thanks!
  • 0

Advertisements







Similar Topics

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

As Featured On:

Microsoft Yahoo BBC MSN PC Magazine Washington Post HP