Jump to content

Welcome to Geeks to Go - Register now for FREE

Need help with your computer or device? Want to learn new tech skills? You're in the right place!
Geeks to Go is a friendly community of tech experts who can solve any problem you have. Just create a free account and post your question. Our volunteers will reply quickly and guide you through the steps. Don't let tech troubles stop you. Join Geeks to Go now and get the support you need!

How it Works Create Account
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