Invalid conversion from BaseClass* to DerivedClass* - c++

I'm trying to use the factory method to return a derived class but the return type is the base class type. From my understanding I thought inheritance would allow me to do this, obviously I am wrong.
WeightExercise and CardioExercise are both derived from Exercise.
I could cast the object but I thought my design would mean I don't have to do that. Can someone point out my mistake please?
Main
ExerciseFactory ExerciseFactoryObj;
WeightExercise *WeightExerciseObj = ExerciseFactoryObj.createExercise(menuselection);
Factory Class
class ExerciseFactory
{
public:
ExerciseFactory();
~ExerciseFactory();
Exercise* createExercise(int exercisetype);
private:
static WeightExercise* createWeightExercise() { return new WeightExercise(); }
static CardioExercise* createCardioExercise() { return new CardioExercise(); }
};
Factory Implementation
Exercise* ExerciseFactory::createExercise(int exercisetype)
{
if ( 1 == exercisetype )
{
return this->createWeightExercise();
}
else if ( 2 == exercisetype )
{
return this->createCardioExercise();
}
else
{
cout << "Error: No exercise type match" << endl;
}
}

You can assign a Derived class returned from the factory to the base class one :
ExerciseFactory ExerciseFactoryObj;
Exercice *WeightExerciseObj = ExerciseFactoryObj.createExercise(menuselection);
Edited:
If you really need to access WeightExerciceObject element use :
WeightExerciceObject * weight = dynamic_cast<WeightExerciceObject *>(ExerciseFactoryObj.createExercise(menuselection));
this will return NULL if the class is not the exact one. You need to check against NULL.

In the main method, this:
WeightExercise *WeightExerciseObj = ExerciseFactoryObj.createExercise(menuselection);
should be this
Exercise *WeightExerciseObj = ExerciseFactoryObj.createExercise(menuselection);
You can't use WeightExercise, because you don't know what specific type of exercise is being returned, it might be a CardioExercise or a WeightExercise, or some other future type you aren't yet aware of.

Related

C++ - How to reserve some class objects to only be instantiated by a certain class

I'm defining a unique_id_generator class, which is kind of, sort of a singleton i.e there is just one instance for a given type_id. There can be many different type_ids, but for a specific type_id, there is just one instance.
Now I want to make sure that type_id = 0 goes to a very specific class. Basically just that specific class can use type_id = 0 and then the rest can be used freely.
I'm wondering through which design pattern can I ensure that happens?
I don't want to control or govern type_ids given in general.
FYI, I'm already using a private constructor to block un-guarded instantiation of the class.
I can't control who instantiates a unique_id_generator first. Also based on design, I don't want to route requests for unique ids through the specific class which gets type_id = 0.
Any thoughts/advice is greatly appreciated.
The only solution I could think of is to define 2 instantiation methods. One public and one private as follows:
#define EXCLUSIVE_CNT 1
class UniqueID
{
public:
friend class MySpecialClass;
static UniqueID * GetInstance(int type_id)
{
assert(type_id >= EXCLUSIVE_CNT);
return Instantiate(type_id);
}
private:
int type_id_;
int seq_id_;
std::map<type_id, UniqueID*> type_to_obj_map_;
UniqueID(int type_id)
{
type_id_ = type_id;
seq_id_ = 0;
}
static UniqueID * GetExclusiveInstance(int type_id)
{
assert(type_id < EXCLUSIVE_CNT);
return Instantiate(type_id);
}
static UniqueID * Instantiate(int type_id)
{
if(type_to_obj_map_.find(type_id) == type_to_obj_map_.end())
{
type_to_obj_map_[type_id] = new UniqueID(type_id);
}
return type_to_obj_map_[type_id];
}
};

Achieve the below syntax(for Factory design patters) in any compiled language? preferably Kotlin, C++

I want to know if the below syntax is available for a compiled langue?
Please do not provide java as it requires the JVM. The design is equivalent to a factory design pattern as we initialize a class once some test passes in normal situations we use lots of if-else statements i.e When we have a range of classes we i.e 10 classes the code becomes clunky
I am trying to create a language transpiled or compiled not decided on that yet and would looking into features capabilities of the already compiled languages currently working with kotlin-native and llvm (not yet sorted llvm integration) it's on startup and that is what I want to consider using.
class A{
}
class B extends A{
}
class C extends A{
}
class D extends A{
}
class E extends A{
}
class F extends A{
}
class G extends A{
}
class H extends A{
}
class I extends A{
}
class J extends A{
}
class K extends A{
}
function getClass(test){
if(test == 1){
return new B()
}else if (test == 2){
return new C()
}else if (test == 3){
return new D()
}else if (test == 4){
return new E()
}else if (test == 5){
return new F()
}else if (test == 6){
return new G()
}else if (test == 7){
return new H()
}else if (test == 8){
return new I()
}else if (test == 9){
return new J()
}else if (test == 10){
return new K()
}
}
let klass = getClass(10)
console.log(`Found class ${klass.constructor.name}`)
class A {
static test(test) {
return test === this.index;
}
}
class B extends A{}
B.index = 1
class C extends A{}
C.index = 2
class D extends A{}
D.index = 3
class E extends A{}
E.index = 4
class F extends A{}
F.index = 5
class G extends A{}
G.index = 6
class H extends A{}
H.index = 7
class I extends A{}
I.index = 8
class J extends A{}
J.index = 9
class K extends A{}
K.index = 10
let klasses = [B, C,D,E,F,G,H,I,G,K];
let klass = new A();
let test = 7;
for (let i = 0; i < klasses.length; i++) {
try {
if(klasses[i].test(test)){
klass = new klasses[i]()
}
} catch (e) {
console.log(e)
}
}
console.log(`Found class ${klass.constructor.name}`);
Can you clarify your question? Your previous question How can I achieve the below syntax in any compiled language? preferably Kotlin, C++ actually seemed clearer to me. Could you maybe give us information on what high-level goal you are trying to achieve?
Are you trying to design a new language? Are you trying to pick a language to implement your new language's parser in?
Going by your code, you are trying to design a language where classes are kept as a list, in order of declaration, and then you want to be able to instantiate all those classes by iterating the list somehow, and the classes are supposed to be able to know their own index in the list for other uses?
Is that what you're trying to do?
In most languages, classes can't be kept in arrays. They aren't actual objects. But some, like Smalltalk, Objective-C, Self or TADS, implicitly create an object for each class that contains additional data (C++ has an atrophied form of this called "runtime type-information", or RTTI).
If your implementation language doesn't do that, you'll have to do that yourself. Create objects that contain a function that creates an object of the right subclass (and maybe contains some other information like the class name or index in the list so you can find it again), and add that "maker" object to a global list. Then just use this global list of factory objects to create your instances.
You're not saying how you are creating your language though. Are you writing a tool that reads a text file in your language and turns it into a source file in an existing language? Then that tool would just have to create the source code for a few additional classes (like, for class B, it would also create a class B_Maker that is a subclass of class A_Maker, but creates a new object of type B, and then it would create some init() function containing code to crete a new object of each maker and add them to the global list).
If you're modifying LLVM or some other existing compiler chain, or trying to do this from scratch, the basic approach would be the same (unless there is already an existing object for each class that you can just extend), but you wouldn't be generating source code, but some other data structures that result in the equivalent code being compiled in the end.
Give us more context, and we might be able to help.

Object instantiation through factory method not giving desire result

In below code snippet I do require to instantiate the object through factory method in order to call the selected adapter (i.e. adapterTwovalue)but while calling through factory method i am not able to get the desire results. When we assign static declared object's address (i.e adapter = &at) it works but with factory i usually get the blank output.
I tried as well with (adapter = new adapterTwo()) to instantiate the object but output string is giving blank results. As per my requirement i need to populate the all the getters in connect function which is pure virtual function to frame the response.Anybody can suggest how to achieve this using factory method.
#include <iostream>
using namespace std;
class IAdapter
{
public:
enum FactoryList { AdapterOnevalue = 0, AdapterTwovalue };
virtual void connect() = 0;
static IAdapter* CreateList(FactoryList);
virtual ~IAdapter() {}
};
class LibraryOne
{
string property;
public:
void SetConnection(string property)
{
this->property = property;
}
string getConnection()const
{
return property;
}
};
//LibraryTwo
class LibraryTwo
{
string broker;
public:
void SetBroker(string broker1)
{
this->broker = broker1;
}
string getBroker() const
{
return broker;
}
};
//adapterOne
class AdapterOne : public IAdapter
{
LibraryOne one;
string constring;
public:
void SetClientconnection(string constring)
{
one.SetConnection(constring);
}
string GetClientconnection()
{
return one.getConnection();
}
void connect()
{
constring = GetClientconnection();
}
};
//Adapter to use library two
class AdapterTwo : public IAdapter
{
LibraryTwo two;
string brokerstring;
public:
void SetClientbroker(string constring)
{
two.SetBroker(constring);
}
string GetClientbroker()
{
return two.getBroker();
}
void connect()
{
string constring = GetClientbroker();
cout << "final value=" << constring;
}
};
IAdapter* IAdapter::CreateList(FactoryList SelectList)
{
IAdapter *ListObject;
switch (SelectList)
{
case AdapterOnevalue:
ListObject = new AdapterOne();
break;
case AdapterTwovalue:
ListObject = new AdapterTwo();
break;
default:
ListObject = NULL;
}
return ListObject;
}
int main()
{
IAdapter *adapter = 0;
//LibraryTwo obj;
AdapterTwo at;
at.SetClientbroker("amqp");
//cout << at.GetClientbroker();
//adapter = &at; it works
adapter = IAdapter::CreateList(IAdapter::AdapterTwovalue);//it doesn't work
//Just do the operation now
adapter->connect();
return 0;
}
You can see the complete solution in below share link.
http://coliru.stacked-crooked.com/a/d8b9d32a1fa989c9
Here is the explanation.
(1) setClientBroker() or all other adapters related setter functionality needs to be implement as a virtual function in Interface with default parameter value " " (blank string).
(2) you need to always use override keyword (c++11) feature in derive class for setters so that compiler will cross check during compilation whether proper virtual method is being overridden or not.
(3) instead of using local raw pointer , always use smart pointer . below is the
implementation link for the same.
http://coliru.stacked-crooked.com/a/2feea991ee90d4a2
With your code I expect the output: final value=.
It will not print final value=amqp cause you need to call SetClientbroker("amqp") on the right adapter object (adapter in your example).
Anyway, I would think about putting a virtual method SetString in the base class, so you could simply do:
int main()
{
IAdapter *adapter = 0;
//LibraryTwo obj;
//AdapterTwo at;
//at.SetClientbroker("amqp");
//cout << at.GetClientbroker();
//adapter = &at; it works
adapter = IAdapter::CreateList(IAdapter::AdapterTwovalue);//it doesn't work
//Just do the operation now
adapter->SetString("amqp");//<---------
adapter->connect();
return 0;
}
EDIT after the comment:
You need to cast the object, at this point (as suggested by #Aconcagua).
But IMHO it's not elegant at all. I think you are going to loose the benefits gained with the factory method.
IAdapter* adapter = nullptr;
AdapterTwo at;
adapter = IAdapter::CreateList(IAdapter::AdapterTwovalue);
You have created two independent objects here (as calling new within createList): at and the one adapter points to.
AdapterTwo at;
at.SetClientbroker("amqp");
Now sure you get the expected output if you let adapter point to at, but how could the other object be aware of the string you set in the first one?
adapter = IAdapter::CreateList(IAdapter::AdapterTwovalue);
adapter->SetClientbroker("amqp"); // (*) !!!
You need to set the broker at the other object, too. As being different objects, you even can set the brokers independently:
AdapterTwo at;
at.SetClientbroker("amqp");
IAdapter* adapter = IAdapter::CreateList(IAdapter::AdapterTwovalue);
adapter->SetClientbroker("aconcagua"); // (*) !!!
Output now would be (if you called connect on both objects):
final value=amqp
final value=aconcagua
Only: The marked lines ((*)) won't compile as your base class does not provide the appropriate setter!
There are now different solutions for this problem. You could, for instance, just cast the object:
// if you are REALLY 100% sure the object is of appropriate type:
static_cast<AdapterTwo*>(adapter)->setClientBroker("...");
// if NOT:
AdapterTwo* a2 = dynamic_cast<AdapterTwo*>(adapter);
if(a2)
a2->setClientBroker("...");
else
// appropriate error handling
You could find a more generic name for the set/get Broker/ClientConnection functions, have them already pure virtual within IAdapter and override them in the two implementing adapter classes, so you could then just call adapter->setXYZ("ampq");. [Edit: according to your comment to the question, not an option in the given case]
My personal favourite is providing an additional parameter to your createList function such that the setter would already be called within the factory - possibly with appropriate default: empty string, if you opt for a std::string parameter, or nullptr in case of char const*. You'd only call the setter if the parameter is not matching the default, of course... Alternatively, you could have two overloads.

How can I verify if I am working with a base or derived object in C++? [duplicate]

This question already has answers here:
Check for derived type (C++)
(6 answers)
Closed 4 years ago.
Let's say I have a class Product and a class AuctionedProduct which derives from Product. I then have a virtual function foo that does 'x' if I'm working with a Product base class and 'y' if it's actually an AuctionedProduct. Given an object, how can I determine which class is actually the one I'm working on?
If you are using inheritance properly, code operating on references of a base class (Product), should not need to know the actual type of the object, but interact with each product the same way.
However, if you really would like to know the actual type, e.g: because of debugging, you can use dynamic_cast:
void f(Product* p)
{
AuctionedProduct* ap = dynamic_cast<AuctionedProduct*>(p);
if (ap) {
// we have an AuctionedProduct
}
else
{
// ap is nullptr, we have a different kind of product
}
}
you can use virtual methods and use different implementation for base class and derived class and use that method for identify object type.
you can find more decription here :
Check for derived type (C++)
Hi you need to use dynamic_cast to find out the object of type like below, dynamic_cast method will return the address of the object if it match with the class type parameter. Also see my comments in the below codes:-
class Product{};
class AuctionedProduct : public Product{};
class NonAuctionedProduct : public Product{};
Product *prod1 = new AuctionedProduct();
Product *prod2 = new NonAuctionedProduct();
AuctionedProduct *ac = NULL;
NonAuctionedProduct *nac = NULL;
ac = dynamic_cast<AuctionedProduct*>(prod1);//here it will return the address as prod1 is a type AuctionedProduct
if(ac != NULL )
{
//ac->dosomething
cout<<"I am class AuctionedProduct<<endl;
}
nac = dynamic_cast<NonAuctionedProduct*>(*prod2);
if(nac != NULL )
{
//nac->dosomething
cout<<"I am class NonAuctionedProduct<<endl;
}
ac = dynamic_cast<AuctionedProduct*>(prod2); //here it will return NULL as prod2 is a object of type NonAuctionedProduct

Partial Mock or new class or what else?

I have a question about testing.
I have a class that returns anomalies. in this class I have two different method that simply returns two different types of anomalies and one that return all anomalies (of both types)
this is the example code:
public interface IAnomalyService
{
IList<Anomaly> GetAllAnomalies(object parameter1, object parameter2);
IList<Anomaly> GetAnomalies_OfTypeA(object parameter1);
IList<Anomaly> GetAnomalies_OfTypeB(object parameter2);
}
public class AnomalyService : IAnomalyService
{
public IList<Anomaly> GetAllAnomalies(object parameter1, object parameter2)
{
var lstAll = new List<Anomaly>();
lstAll.AddRange(GetAnomalies_OfTypeA(parameter1));
lstAll.AddRange(GetAnomalies_OfTypeB(parameter2));
return lstAll;
}
public IList<Anomaly> GetAnomalies_OfTypeA(object parameter1)
{
//some elaborations
return new List<Anomaly> { new Anomaly { Id = 1 } };
}
public IList<Anomaly> GetAnomalies_OfTypeB(object parameter2)
{
//some elaborations
return new List<Anomaly> { new Anomaly { Id = 2 } };
}
}
class Anomaly
{
public int Id { get; set; }
}
I've created the tests for the two method that retrieve the anomalies of type A and type B (GetAnomalies_OfTypeA and GetAnomalies_OfTypeB).
Now I want to test the function GetAllAnomalies but I'm not sure what I have to do.
I think I have to way for testing it:
1) declare GetAnomalies_OfTypeA and GetAnomalies_OfTypeB in class AnomalyService as virtual, make a mock of the Class AnomalyService, and using Moq I can set CallBase as true and mock the two method GetAnomalies_OfTypeA and GetAnomalies_OfTypeB.
2)move the method GetAllAnomalies in another class called AllAnomalyService (with interface IAllAnomalyService) and in its constructor I will pass an interface of IAnomalyService and after I can test the GetAllAnomalies mocking the IAnomalyService interface.
I'm new at unit testing, so I don't know which solution is better, if is one of the mines or another one.
Can you help me?
thank you
Luca
Mocking is a good tool when a class resists testing. If you have the source, mocking is often not necessary. Try this approach:
Create a factory which can return AnomalyServices with various, defined anomalies (only type A, only type B, both, none, only type C, ...)
Since the three types are connected in some way, you should check all three in each test. If only anomalies of type A are expected, you should check that GetAllAnomalies returns the same result as GetAnomalies_OfTypeA and GetAnomalies_OfTypeB returns an empty list.