polymorhism

Started by
13 comments, last by chairthrower 15 years, 12 months ago
Ok I sat up about 6 hrs yesterday trying to do an example of polymorphism ….this is how I have it im gonna first typing each class and header im trying to call a function and change it to do something else don’t quaote my exact programming this is not the actually program declarations (close) this is only psudeo at best . I have getting two errors one for indirect uses of pointer and the other says invalid call of virtual function , function already contains body in .obj Text the goal of this example is to continue reuse my open text function and then resue it somewhere else using polymorhism any help would be greatly apprecaited

Text.h :

//base class 

 

#Ifndef TEXT_H

#define TEXT_H

 

#include <iostream>

 

using namespace std;

 

 

class Text

 

 Text():

//default constructor 

 

void openOneText();

 //function to open 1 text file 

// trying to use this function for polymorphism 

 

void setNameOneText();

//sets name for one text file 

 

setTwoTextFiles();

setTwoTextName()

 

private :

 

char *solo

//variable for setNameOneText

 

char *fileName1

 

char *fileName2

 

text.cpp:

 

#include “Text.h"

 

Text::Text()

{

public :

     ///default constructor

}

void Text:: void setNameOneText();

 

{

    ///sets variable solo for text file name

 

}

void Text:: openOneText();

{

            ifstream fin;

            fin.open(solo);

            fin.close();

        

          ///working function

}

 

 

            Message.h

         //derived class

 

 

#Ifndef Message_H

#define Message_H

 

#include <iostream>

 

using namespace std;

 

class Message : public Text 

{

public:

            message ();

            // default constructor

                        

            void firstUserChoice();

            void secondUsersChoice();

            void openOneText();   //trying to set up for polymorphism

            virtual void openOne();//I think this is what is need to use for function use 

 

 

}

 Message .cpp

 

#include “Message.h"

 

Message::message();

{

}

 

void firstUserschoice ()

{

            Text temp;

            

            cout<< “welcome"<<endl;

            temp.openOneText();

 

}

 

void Text::openOneText();

{

            //restating original function im not sure if this is needed    

            fstream fin;

            fin.open(solo);

            fin.close();

}

 

virtual void openOne();

{           

            char  answer

            char *carName;

            

            openOneText();

do

 

{  

                        cout << " Please Enter Your VehicleName: " << endl;

 

                        cin >> carName;

 

                        cout << "You have entered " << carName << ". Is this correct? (y/n)" << flush;

                        cin >> answer;

 

 

                        if ( static_cast<int>( playerName.length() ) > 10) 

                        {

                        

 

                        cout << " You have exceed 10 chracters.  Try Again" << endl;

                        answer = 'n';

                        }

                        else if ((answer == 'Y') || (answer == 'y'))

                        {

                        cout << playerName << " Let's Begin "<< flush;

                        cin.clear();

 

                        cin.ignore(500,'\n');

 

 

                        }

                        else if ((answer == 'N') && (answer == 'n'))

                        {

                        cout <<  " Please Re-enter. " << endl;

                        }

 

 

} while ((answer == 'N') || (answer == 'n'));

 

}

 

 

main .cpp

{

            Message  showUserText;

            Message *waitForUserInput new (I cant remember  what I had here since my file is at home)

            Message Input;

 

            showUser.Text.set setNameOneText(“splash.txt);

            *waitUserInput->input ;/// this is where I am trying to call function I set up in message 

             

}


Advertisement
I suggest that you look at the free book in my sig (2nd link) to learn more about C++, as you have some very fundamental mistakes in your code (inheriting from a function doesn't make sense, for example).

This probably isn't what you wanted to hear, but it will make your life easier in the long run.
Quote:Original post by shadowfire36
Ok I sat up about 6 hrs yesterday trying to do an example of polymorphism ….this is how I have it im gonna first typing each class and header im trying to call a function and change it to do something else don’t quaote my exact programming this is not the actually program declarations (close) this is only psudeo at best .


If you've actually written code, you should show the actually-written code. We're not psychic.
From my understanding, a simply polymorphism example would be:

class Monster{public:     Monster();     Monster(int, int);     void printMonsterStats();private:     int _health;     int _strength;};Monster Monster(){     _health = 0;     _strength = 0;}Monster Monster(int health, int strength){     _health = health;     _strength = strength;}void Monster::printMonsterStats(){     cout<< _health << endl;     cout<< _strength << endl;}


Now, to me that looks more like function overloading but I am no expert I am just reading this example out of a book and that is what the book shows as a small example of polymorphism.

(If its not someone please let me know so I can delete my post)
C# code using trite car analogy, becase the analogy is easy and abstract/virtual is clearer in c# than c++ style virtual foo() =0. Look how the inheriting classes override the functionality of their parents to provide different behaviour if required, but can still be referred to as their parents and operated on. They use their parents interface but define their own implementation.

public class MovingObject    {        private float speed;        public float Speed { get { return speed; } protected set { speed = value; } }        public void PrintSpeed() { Console.WriteLine(speed); }    }    abstract public class Vehicle : MovingObject    {        abstract public void PrintName();        virtual public void Accelerate() { }    }    public class Car : Vehicle    {         public override void PrintName() { Console.WriteLine("Car"); }        public override void Accelerate() { Speed = Speed + 10; }    }    public class Bike : Vehicle    {        public override void PrintName() { Console.WriteLine("Bike"); }        public override void Accelerate() { Speed = Speed + 5; }    }    public class ChargedBike : Bike    {        private bool charged = false;        public bool Charged { get { return charged; } set { charged = value; } }        public override void PrintName() { Console.WriteLine("ChargedBike"); }        public override void Accelerate()         {            if (charged)            {                Speed = Speed + 50;            }            else            {                base.Accelerate();            }        }    }    class Program    {        static void Main(string[] args)        {            //Vehicle v = new Vehicle(); // Compile error as abstract            Bike bike = new Bike();            Car car = new Car();            ChargedBike chargedbike = new ChargedBike();            bike.PrintName();            car.PrintName();            chargedbike.PrintName();            //add all vehicles to list            List<Vehicle> vehicleList = new List<Vehicle>();            vehicleList.Add(bike);            vehicleList.Add(car);            vehicleList.Add(chargedbike);            foreach (Vehicle v in vehicleList) { v.PrintSpeed(); }            foreach (Vehicle v in vehicleList) { v.Accelerate(); }            foreach (Vehicle v in vehicleList) { v.PrintSpeed(); }            chargedbike.Charged = true;            chargedbike.Accelerate();            foreach (Vehicle v in vehicleList) { v.PrintSpeed(); }            Console.Read(); //wait        }    }



For what it's worth this prints:

BikeCarChargedBike000510551055



If you are confused, compile this and step through, watching for which code path is executed when the child class objects call the parent interface methods. Hope this helps, if you have any questions or corrections please post back.
Quote:Original post by Gage64
I suggest that you look at the free book in my sig (2nd link) to learn more about C++, as you have some very fundamental mistakes in your code (inheriting from a function doesn't make sense, for example).

This probably isn't what you wanted to hear, but it will make your life easier in the long run.


im scared your a programmer if u didn't read this is a pseudo code
Why? There's still plenty wrong with it, even as pseudocode. There's no reason to get snippy.

If you want help with your real code, show us your real code, as Zahlman says. Otherwise, take the advice you've been given with respect to your pseudocode.
Quote: Why? There's still plenty wrong with it, even as pseudocode. There's no reason to get snippy.

If you want help with your real code, show us your real code, as Zahlman says. Otherwise, take the advice you've been given with respect to your pseudocode.


im not getting snippy why would i need to take advice if im asking for help TO build something with polymorism , i would think if im starting a topic on it, someone may think i already know some fundamentals of programming already ..im just surprise how some many people get attitudes over something that does not even exist ...i just feel some people are in a way are to literal and a bit on the extreme side but im not downing anyone .. im here to learn not to get fussed at like im a child .(subject dropped)

now that im home i can upload my code i dont think its really that hard or anyone to give me an idea i dont have net access or visual studio at work so i made my post while i was thinking of the code it couldnt get to my files,but i wanted more insight before i got home...

to my issue now i have a function in my text.cpp named test 1 and a virtual function called test 2 the idea is to set a simple cout in these two functions and allocate memory a variable and then i setup the function so it can open a file somewhere else,get some simple input cout a message from a message class
now what i was trying to do in choices.cpp is to call each of the in and display each message in order

sample run would be ...

1st variable(function) = this is an example of
2nd variable(function) = polymorphism
3rd variable(function) = if this isnt
4th variable(function) = polymorphism
5th variable(function) = i dont no what
cout << is << endl;


Text.h
//base class#ifndef TEXT_H#define TEXT_H#include <fstream>#include <iostream>#include <string>using namespace std;class Text// fucntion class to open and close text files {public:	void setFileName(char* name, char* name2);		 //sets file name when opening 2 text display		void setTextName(char* name3);	     //set file name for 1 text display 	void twoTextFile();	     //opens 2 text files at  1 time 	void oneTextFile();       //open 1 text file at a time		void test();///setup for trying to use polymorphism	virtual void test1();///setup for trying to use polymorphism      	Text();	//default constructorprotected:	char *solo;//protected variable 	char *file1;//protected variables		char *file2;//protected variables};#endif


Text.cpp
#include <iostream>#include "Text.h"void Text::setTextName(char *name3){	solo = name3 ;// sets variable name for one text file}void Text::oneTextFile()// function for opening one text file {	ifstream fin;	fin.open(solo);	string temp;	while ( !fin.eof() )	{		getline(fin, temp);		cout << temp << endl;	}		fin.close();	cin.clear();}void Text::setFileName(char *name,char *name2){		file1 = name;	file2 = name2;	}/// right here ///i have to fucntions 1 opens one file at time the other opens void Text::twoTextFile(){	ifstream fin;	fin.open(file1);	string temp;	while ( !fin.eof() )	{		getline(fin, temp);		cout << temp << endl;	}	fin.close();	ifstream fin2;	fin2.open(file2);		while ( !fin2.eof() )	{		getline(fin2, temp);		cout << temp << endl;	}	fin2.close();	cin.clear();}Text::Text(){	}void Text::test()//function for polymorhism{	cout << "This better be : "<< endl;}void Text::test1()//function for polymorhism{	cout << "Or i dont know what:  " << endl;}


Message.h
// derived class#ifndef MESSAGE_H#define MESSAGE_H#include <iostream>#include "Text.h"using namespace std;class Message : public Text{public:     void firstUserSelection();        // 1st user option message	 		 void secondUsersSelction();		  void test();//not sure of this is right	  	  Message();	    //default constructor};#endif 


Message.cpp
#include "Message.h"void Message::firstUserSelection(){		cout << "*** Welcome please make a selection . ***" << endl;	cout << "To select an item, enter " << endl;	cout << " [1] To start Car Buyer  " << endl;	cout << " [2] To View Nissan Cars " << endl;	cout << " [3] To View Toyota Cars " << endl;	cout << " [4] To Quit " << endl;	cout << " [5] to view polymorphism " << endl;}void Message::secondUsersSelction(){		system("cls");	cout << "*** What type of vehcile are you intrested in ?  ***" << endl;	cout << "To select an item, enter " << endl;	cout << " [1] For Hatchbacks  " << endl;	cout << " [2] For Sedans " << endl;	cout << " [3] For Coupes " << endl;	cout << " [4] To Quit " << endl;	}Message::Message(){}void Message::test()//function to change previous fuction {		int example;	ifstream fin;	fin.open("poly.txt");	string temp;	while ( !fin.eof() )	{		getline(fin, temp);		cout << temp << endl;	}						cout << "how many cars are in list ?" << endl;	cin >> example ;			if(example = 8)	{ 		cout << "Sweet !!!  YOU CAN COUNT !! " << endl;                fin.close();	        cin.clear();	}	else 	{	cout <<" try again " << endl;	}}


choices.h
[source="cpp"]#ifndef CHOICES_H#define CHOICES_H#include <fstream>#include <iostream>#include <string>#include "Text.h"#include "Message.h"using namespace std;class Choices: public Text{public:	 void firstUsersChoice();	 void secondUsersChoice(Message msg, Text txt);         void enterUsersInfo();	 void carType();	 };#endif


choices.cpp
#include "Choices.h"#include "Message.h"#include "Text.h"void Choices::firstUsersChoice(){	int menu = true;        int choice;	Text toyota;        Text nissan;	Message back;	Text goodbye;	Choices purchase;	Message showUserOptions;	Message *data = new Message();	Message message;	Text text;	Text *store = &message;	Message *store1 = &message;				  	do // beginning of loop for user 1st selection	{ 	back.firstUserSelection();			cin >> choice; // choice selection for users		switch (choice)// begin switch for user selection		{		case 1:			secondUsersChoice(back, goodbye);			break;		case 2:			nissan.setFileName("nissan.txt","nline.txt");			nissan.twoTextFile();			break;		case 3:			toyota.setFileName("toyota.txt","tline.txt");			toyota.twoTextFile();		   			break;		case 4:			goodbye.setTextName("goodbye.txt");			goodbye.oneTextFile();			break;		case 5:			text.test();			store1->test();			text.test1();			data->test();			cout << " is " << endl;			//store->test();// currently not working			//store1->test1();//currently not working			 									default : //handles invaild choice 			 		 cout << " "<< endl;		 cout << " "<< endl;		 cout << " "<< endl;		 cout << " "<< endl;			 cout << "***** 'Please read options again  & Then re-enter a vaild choice.'*****" << endl;		 cout << " "<< endl;		 cout << " "<< endl;		 cout << " "<< endl;		 cout << " "<< endl;		 break;		          		}		system("PAUSE");		system("cls");		 	}while (choice != 4);	 }void Choices::enterUsersInfo(){	Message back;	char answer;	string name;	string vehicleName;	Choices purchase;	do	{  				ofstream receipt("car.txt");		cout << " Please Enter The Type of You are Intrested in   Vehicle: " << endl;		cin >> name;		cout << "You have entered " << name<< ". Is this correct? (y/n)" << flush;		cin >> answer;		if ( static_cast<int>( vehicleName.length() ) > 10) 		{					cout << " You have exceed 10 chracters.  Try Again" << endl;			answer = 'n';		}			else if ((answer == 'N') || (answer == 'n'))		{			cout <<  " Please Re-enter. " << endl;		}	} while ((answer == 'N') || (answer == 'n'));				}void Choices::carType(){    int menu = true;    int choice;    Text carType;    Message back;    Text goodbye;    Choices purchase;					  	do // begining of loop well 	{ 			cin >> choice; // choice selection for users		switch (choice)// begin switch for user selection		{		case 1:			purchase.enterUsersInfo();			carType.setTextName("hatchback.txt");			cout << " These Are Current Models: " << endl;//need clear value 			carType.oneTextFile();							    			break;		case 2:			carType.setTextName("sedan.txt");			cout << " These Are Current Models: " << endl;			carType.oneTextFile();			purchase.enterUsersInfo();			break;		case 3:			carType.setTextName("coupe.txt");			cout << " These Are Current Models: " << endl;			carType.oneTextFile();			purchase.enterUsersInfo();		case 4:			goodbye.setTextName("goodbye.txt");			goodbye.oneTextFile();			return  ;			break;					default : //handles invaild choice 			 		 cout << " "<< endl;		 cout << " "<< endl;		 cout << " "<< endl;		 cout << " "<< endl;			 cout << "***** 'Please read options again  & Then re-enter a vaild choice.'*****" << endl;		 cout << " "<< endl;		 cout << " "<< endl;		 cout << " "<< endl;		 cout << " "<< endl;		 break;		}			 	}	 while (menu != 4);	 }void Choices::secondUsersChoice(Message msg, Text txt){	int userChoice;	do	{		msg.secondUsersSelction();		cin >> userChoice;		switch (userChoice)		{		case 1:			txt.setTextName("hatchback.txt");			txt.oneTextFile();			system("PAUSE");			break;		case 4:			cout << "Back the the main menu..." << endl;			break;		default:			cout << "That is not a valid choice" << endl;		}	}while (userChoice != 4);}



























In order to use polymorphism, you must make use of inheritance and virtual functions. Here is a simple example.
class Athlete{public:   Athlete();   virtual ~Athlete(); // Must have a virtual destructor to avoid pitfalls.   void Compete() {cout << "I compete in anything!" << endl;}};class Runner : public Athlete{public:   Runner();   ~Runner(); // Base class destructor was already declared virtual, all               //  derived class destructors will automatically also be virtual               //  (I believe).  No need to re-state 'virtual'   void Compete() {cout << "I compete in marathons!" << endl;}};

And here's how you could use it.
// Create a Runner object.Runner* p_runner = new Runner;// Create an Athlete pointer that points to the Runner object.Athlete* p_athlete = dynamic_cast<Athlete*>(p_runner);p_athlete->Compete();

In the above example, I created a Runner object. Next, because an Athlete is a base to a Runner, I was able to assign the Runner object to the Athlete pointer. However, doing this doesn't strip the Runner object of still being a Runner. Therefore, when I call Compete() on the Athlete pointer, it prints out "I compete in marathons!".

This is the power of polymorphism. You might have a base class pointer to an object (p_athlete), not know or care what the actual instantiated class is (as long as it is an Athlete class or another class derived from Athlete), and the appropriate method will be called. If p_athlete points to an Athlete object,
it would print "I compete in anything!". If it points to a Runner, it would print "I compete in marathons!". If it points to a Jumper class that derived from Athlete, it might print "I like to jump high!".

This allows to you do something like have all your athletes compete by looping through a list of base class pointers and calling the same function for all types of athletes.
for (list<Athlete*>::iterator iter = athlete_list.begin(); iter != athlete_list.end(); ++iter){   (*iter)->Compete();}
Quote:
Athlete* p_athlete = dynamic_cast<Athlete*>(p_runner);


A pointer to a derived class can be implicitly converted to a pointer to a base class, so the cast is not needed. You can just write:

Athlete* p_athlete = p_runner;


dynamic_cast is used to cast a base class pointer/reference to a derived class pointer/reference. This cannot be done implicitly because if you have a pointer to an Athlete, you can't know at compile-time whether it's really pointing to an Athlete or to something derived from it. You have to perform a runtime check to find out, which is what dynamic_cast allows you to do.

This topic is closed to new replies.

Advertisement