Is there a better way to access the base class operator overload? I'm using casting, and it works just fine, just wondering if there is a better way. Is this bad/ugly code?

class StrategyKey
{
public:
	StrategyKey(){}
	~StrategyKey(){}

	StrategyKey(const char* strA):
		str_strategy(strA)
	{}

	friend bool operator< (const StrategyKey& stratKeyA, const StrategyKey& stratKeyB)
	{
		if (stratKeyA.str_strategy < stratKeyB.str_strategy)
			return true;
		else
			return false;
	}
	std::string str_strategy;
};

class TechniqueKey : public StrategyKey
{
public:
	TechniqueKey(){}
	~TechniqueKey(){}

	TechniqueKey(const char* strA, const char* strB): StrategyKey(strB),
		str_technique(strA)
	{}

	friend bool operator< (const TechniqueKey& stratKeyA, const TechniqueKey& stratKeyB)
	{
		if (stratKeyA.str_technique < stratKeyB.str_technique)
			return true;
		else if (stratKeyA.str_technique == stratKeyB.str_technique)
			return (StrategyKey)stratKeyA < (StrategyKey)stratKeyB;
		else
			return false;
	}
	string str_technique;
};

Casting in that example if fine. But looking at your code, you are probably going to want to encapsulate the member variables, that way operator< does not have to be a friend function.

#include <string>
#include <iostream>
using namespace std;

class StrategyKey
{
public:
	StrategyKey(){}
	~StrategyKey(){}

	StrategyKey(const char* strA):
		str_strategy(strA)
	{}
       virtual const std::string& getStrategyValue()const{ return str_strategy; }
private:	
	std::string str_strategy;
};

class TechniqueKey : public StrategyKey
{
public:
	TechniqueKey(){}
	~TechniqueKey(){}

	TechniqueKey(const char* strA, const char* strB): StrategyKey(strB),
		str_technique(strA)
	{}
        const std::string& getStrategyValue()const{ return str_strategy; }
private:
	string str_technique;
};

bool operator< (const StrategyKey& stratKeyA, const StrategyKey& stratKeyB){
 return stratKeyA.getStrategyValue() < stratKeyB.getStrategyValue();
}

bool operator< (const TechniqueKey& stratKeyA, const TechniqueKey& stratKeyB){
 const int cmp = stratKeyA.getStrategyValue().compare( stratKeyB.getStrategyValue() );
 if( cmp != 0 ) return cmp < 0;
 else{ //same so compare base values
   return dynamic_cast<const StrategyKey&>(stratKeyA) < stratKeyB; 
 }
}
commented: Thanks! I need to read up on friend functions. +2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.