943,670 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 1090
  • C++ RSS
Mar 24th, 2009
0

Making Derived Class Object Equal To Base Class Object

Expand Post »
I know that you can make a derived class object equal to a base class object, but I don't know how to do it the other way around. Here's the part of my code that I'm having difficulty with (Note: Animal is base class; Lion and Dog are derived classes).

// main.cpp
#include <iostream>

using std::cout;
using std::endl;

#include "animal.h"
#include "lion.h"
#include "dog.h"

int main()
{
    Animal a1( 0, 0 );
    Dog d1( 60, 120, "Fido" );
    Dog d2(0,0,"Toto");
    a1 = d1;
    cout << "Animal 1 now has the same height and weight as dog 1\n";
    a1.print();
    d2 = a1;
    cout << "Dog 2 now has the same height and weight as animal 1\n";
    d2.print();
    system("pause");
    return 0;
    
} // end main

The error message I get suggests that I need to overload the = operator to perform this, but for this assignment, I don't believe we are allowed to do that. How else can you do this?
Reputation Points: 10
Solved Threads: 0
Newbie Poster
DallasEvertts is offline Offline
10 posts
since Mar 2009
Mar 24th, 2009
0

Re: Making Derived Class Object Equal To Base Class Object

I'm not sure if C++ permits that.
Better you can try
Animal* a1 = new Animal();
Animal* d1 = new Dog()

Then you can use dynamic_cast, if needed
Reputation Points: 12
Solved Threads: 8
Junior Poster in Training
kbshibukumar is offline Offline
65 posts
since Jan 2009

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: help....inventory system...
Next Thread in C++ Forum Timeline: help with overload of operator >>





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC