473,586 Members | 2,855 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Instantiating a Derived from a Base

Hi,

I was learning about RTTI when I ran across this example. This line,
out of the example, confused me. It is declaring a pointer to a base
type and instantiating it with a derived class. I can say the
words ... yet I don't get it. What do I have, a base or a derived? Can
anyone push me in the right direction.

abc *abc_pointer = new xyz();
/*
-------------------------------------------------------------------------------------------------
*/

#include <iostream>

class abc // base class
{
public:
virtual void hello()
{
std::cout << "in abc";
}
};

class xyz : public abc
{
public:
void hello()
{
std::cout << "in xyz";
}
};

int main()
{
abc *abc_pointer = new xyz();
xyz *xyz_pointer;

// to find whether abc is pointing to xyz type of object
xyz_pointer = dynamic_cast<xy z*>(abc_pointer );

if (xyz_pointer != NULL)
std::cout << "abc pointer is pointing to a xyz class object"; //
identified
else
std::cout << "abc pointer is NOT pointing to a xyz class object";

return 0;
}

May 14 '07 #1
3 1659
On May 13, 10:36 pm, Randy <gast...@sympat ico.cawrote:
Hi,

I was learning about RTTI when I ran across this example. This line,
out of the example, confused me. It is declaring a pointer to a base
type and instantiating it with a derived class. I can say the
words ... yet I don't get it. What do I have, a base or a derived? Can
anyone push me in the right direction.

abc *abc_pointer = new xyz();
Look at it this way, all derived objects are really base objects that
have been repackaged or specialized. That means you can point to
either the whole object or the underlying base package.
A derived object does not have a base object in it. A derived object
is_a base object.

In the above code you have a derived object but the pointer holds that
base's address.
If you have the base's address you can access the derived object if
you need to.
Read about downcasting and upcasting in C++.

struct Bird { ... };
struct Eagle : public Bird { ... };
struct Pigeon : public Bird { ... };

int main()
{
Eagle eagle; // a special type of Bird
Pigeon pigeon; // another special type of Bird
Bird* p_bird = &eagle; // base ptr points to Eagle
p_bird = &pigeon; // ok, base ptr changed to point to Pigeon

Eagle* p_eagle = &eagle; // ok, no problem
p_eagle = &pigeon; // error !!!
}
>
/*
-------------------------------------------------------------------------------------------------
*/

#include <iostream>

class abc // base class
{
public:
virtual void hello()
{
std::cout << "in abc";
}

};Do a search for upcasting and downcasting

class xyz : public abc
{
public:
void hello()
{
std::cout << "in xyz";
}

};

int main()
{
abc *abc_pointer = new xyz();
xyz *xyz_pointer;

// to find whether abc is pointing to xyz type of object
xyz_pointer = dynamic_cast<xy z*>(abc_pointer );

if (xyz_pointer != NULL)
std::cout << "abc pointer is pointing to a xyz class object"; //
identified
else
std::cout << "abc pointer is NOT pointing to a xyz class object";

return 0;

}

May 14 '07 #2
abc *abc_pointer = new xyz();

@Salt_Peter Thank you for your time and examples. I get it now after
some reading and practice. I read up on up/down casting as well.

Base and derived are the same object. In the example, I have created a
new instance of a derived class but the pointer I created to it points
to it's base. I am pointing to a different "schema" of the same
object. I tested and, as expected, I couldn't access the derived
object's methods ... just the base methods. I had to downcast before I
could call the derived objects methods. ... all within the same
object.

May 14 '07 #3
On May 15, 8:09 am, Randy <gast...@sympat ico.cawrote:
abc *abc_pointer = new xyz();

Base and derived are the same object. In the example, I have created a
new instance of a derived class but the pointer I created to it points
to it's base. I am pointing to a different "schema" of the same
object. I tested and, as expected, I couldn't access the derived
object's methods ... just the base methods. I had to downcast before I
could call the derived objects methods. ... all within the same
object.
That's right. Note that your code has a memory leak because
you never delete the object, and even if you did write:
delete abc_pointer;

it would cause undefined behaviour because the class
does not have a virtual destructor.

If you plan on deleting objects through a pointer to their
base class then the base class needs to have a virtual
destructor. This is so that 'delete' knows that it is not
just destructing a Base object.

May 14 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1560
by: Anand | last post by:
class base: def __setattr__(self,attr,key,*unexpected): print "Base Class :",attr,key,unexpected,self.__dict__ self.__dict__ = key def __getattr__(self,attr,*unexpected): print "Base Class :",attr,unexpected,self.__dict__ return self.__dict__ class derived(base): def __setattr__(self,attr,key,*unexpected):
2
1977
by: Christian Engström | last post by:
When I compile the below program with Microsoft Visual C++ version 6, I get the results I expect, which is that the program should write out base() derived() base() derived(derived) When I try to compile it with gcc, I instead get the compiler error message
9
1791
by: Larry Woods | last post by:
I have a method in my base class that I want ALL derived classes to use. But, I find that I can create a "Shadow" method in my derived class that "overrides" the method in my base class. Can't figure out what attribute to put on the base class method to prevent this. TIA, Larry Woods
4
5237
by: Jeff | last post by:
The derived class below passes a reference to an object in its own class to its base calss constructor. The code compiles and will run successfully as long as the base class constructor does not attempt to access the object -- since m_object is not actually created and initizialized until after the base constructor has been called. Any...
6
2481
by: Taran | last post by:
Hi All, I tried something with the C++ I know and some things just seem strange. consider: #include <iostream> using namespace std;
24
39138
by: AtariPete | last post by:
Hey All, I have a C# question for you regarding up casting (base to derived). I was wondering about the most elegant way (readable, less code) to cast from a base type to its derived type. Please consider the following two classes: class Base { private int m_valA;
2
2631
by: Jessica | last post by:
I have a base class and a derived class, but I am getting errors when I try to access functions of the derived class. Simplified version of my code is as follows: //////////////// // test2.hh class BaseClass {
7
1712
by: Jim Langston | last post by:
This is something someone was asking in irc. I really don't need to do this right now, but may have to in the future. The following code is in error (marked). #include <iostream> #include <string> class Base { public:
10
4070
by: blangela | last post by:
If I pass a base class object by reference (likely does not make a difference here that it is passed by reference) as a parameter to a derived class member function, the member function is not allowed to access the protected data members of the base object. This surprises me. Can someone explain why this is? I suspect there is a good...
0
7911
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8338
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7954
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8215
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6610
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5390
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3836
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3864
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2345
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.