Reputation: 4990
The switch statement in this code does not work. It should define (global) variable x to be instance of class A if the user press 1 and of class B if the user press 2. I would like to print A if user presses 1 and print B if she presses 2. I want to use the "x.print()" statement, where x is either class A or class B, depending on the input.
#include <iostream>
using namespace std;
class A{
public:
void print(){cout<<"A";}
};
class B{
public:
void print(){cout<<"B";}
};
int main() {
int choice;
cout<<"Press 1 to print A\nPress 2 to print B\n";
cin>>choice;
//I know the following does not work, it's just to show what I want to do
switch (choice){
case 1: A x;
break;
case 2: B x;
break;
}
x.print();
return 0;
}
Upvotes: 0
Views: 131
Reputation: 10655
Try this code. It use polimorphism to get what do you want:
#include <iostream>
using namespace std;
class Base {
public:
virtual void print() = 0;
};
class A : public Base{
public:
void print(){cout<<"A";}
};
class B : public Base{
public:
void print(){cout<<"B";}
};
int main() {
int choice;
cout<<"Press 1 to print A\nPress 2 to print B\n";
cin>>choice;
Base *x = NULL;
//I know the following does not work, it's just to show what I want to do
switch (choice){
case 1: x = new A();
break;
case 2: x = new B();
break;
}
x->print();
delete x;
return 0;
}
Upvotes: 1
Reputation: 9380
You can modify your answer as
#include <iostream>
using namespace std;
class super
{
public:
virtual void print() = 0;
};
class A: public super{
public:
void print(){cout<<"A";}
};
class B: public super{
public:
void print(){cout<<"B";}
};
int main() {
int choice;
cout<<"Press 1 to print A\nPress 2 to print B\n";
cin>>choice;
super* x;
switch (choice){
case 1: x = new A() ;
break;
case 2: x = new B();
break;
}
x->print();
return 0;
}
In this, we are creating an interface which is implemented by both class A and class B. And then using runtime polymorphism, we are creating the object of required class.
Upvotes: 1
Reputation: 46
It seems like what you are trying to do is create similar object based on conditions. For this I would suggest inheritance.
class Base{
public:
virtual void print()=0;
};
class A : public Base{
public:
void print(){cout << "This is class A\n";}
}
so main would look like:
Base* x = NULL;
switch (choice){
case 1: x = new A();
break;
case 2: x = new B();
break;
}
This is what it seems like you are trying to do.
Upvotes: 1
Reputation: 24351
You're not going into detail as to what is actually broken but from a quick glance at your code, there is a bunch of problems in there:
x.print()
.x.print();
. You have to make sure the classes are related, either by deriving one from the other or by giving both classes a common ancestorUpvotes: 1