473,385 Members | 1,396 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Instantiating Objects

2
Hello All-

I have always been curious about something in regards to instantiating classes, and since C++ programmers are always the experts, I am sure that you will know the answer.

So, say I were to create a class called animal and then create a virtual method called animal::speak().

Now, say I create a class named cat that inherits from animal, but overrides the speak() method. When the object is created on the heap, how are the functions placed in memory. Are they just pointers to the main declaration of cat.

Specifically, if I instantiate an instance of cat on the heap and then cast it to an animal, if I call the speak method, it still uses the cat::speak() method. How is it that it knows it is a cat::speak() and not an animal::speak()?

I know I am probably making this question more confusing that it really is, so let me know if you would like some code examples.


Cheers-
Chris
Dec 13 '07 #1
2 2174
weaknessforcats
9,208 Expert Mod 8TB
We're not supposed to reveal the inner secrets of C++. Otherwise you will find out that what's happening is simple and you will have no further use for us.

When you create an object in C++, all that's created are the data members. The class methods are functions and they reside in the code segment of the executable to which you have no access. That means all object use the same single set of methods.

In your animal/cat scenario, if you create a cat and pass it to a function expecting an animal pointer or reference, and inside the function call the speak method, you will get the animal::speak() since the function argument is an animal pointer or reference. The cat-ness has been lost.
Expand|Select|Wrap|Line Numbers
  1. class animal
  2. {
  3.      public:
  4.        void speak();
  5. };
  6. void animal::speak()
  7. {
  8.     cout << "Generic noise" << endl;
  9. }
  10. class cat : public animal
  11. {
  12.      public:
  13.          void speak();
  14. };
  15. void cat::speak()
  16. {
  17.     cout << "Meow" << endl;
  18. }
  19. void TheTest(animal* a)
  20. {
  21.     a->speak();
  22. }
  23. int main()
  24. {
  25.      cat obj;
  26.     TheTest(&obj);     //you see "Generic noise"
  27. }
  28.  

The next thing is to make the animal::speak() a virtual function. The code below is exactly the same as the code above with the exception that the animal::speak() method has been made virtual:
Expand|Select|Wrap|Line Numbers
  1. class animal
  2. {
  3.      public:
  4.        virtual void speak();
  5. };
  6. void animal::speak()
  7. {
  8.     cout << "Generic noise" << endl;
  9. }
  10. class cat : public animal
  11. {
  12.      public:
  13.          void speak();
  14. };
  15. void cat::speak()
  16. {
  17.     cout << "Meow" << endl;
  18. }
  19. void TheTest(animal* a)
  20. {
  21.     a->speak();
  22. }
  23. int main()
  24. {
  25.      cat obj;
  26.     TheTest(&obj);     //you see "Meow"
  27. }
  28.  
What has happened here is that the virtual function causes the compiler to create a virtual function table (VTBL) that contains the addresses of the classe's virtual function's, whether inherited or overriden.

In your case the VTBL for cat contains the address of cat::speak(). You see, making the base class method virtual also makes the derived class method virtual. Finally, the address of the VTBL itself is put inside your cat object.

There is one VTBL for all cat objects.

Now when you are inside TheTest(animal* a), the compiler has generated code to access your object and get that VTBL pointer, then go to the VTBL and locate the cat::speak entry and then call that function by its address. And Presto! Meow.

Take the virtual out of the animal class, the VTBL is not created, and when you get to TheTest(anumal* a) no code is generated for a VTBL so all you get is animal::speak().

And that, is how object-oriented programming is implemented in C++: virtual functions.

Try doing a sizeof(cat). When the animal::speak()is not virtual, you get 1. When animal::speak() is virtual, you get 4. That 4 is enough memory to hold the address of that VTBL.
Dec 13 '07 #2
sifl
2
Thanks a million for the help!!

I knew you would have the answer. I'm in a VB.NET class right now (not by choice... work is paying for it), and the instructor didn't know the answer to that question. Their response was that there is no reason to know, so why would someone care.

Although, there is no real explanation for why I needed to know that, at least C programmers respect the fact that some of us just try to understand everything, wheter we need to or not.

Thanks again for your help.
Dec 13 '07 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: SammySAm | last post by:
I have a set of XSD's that I have to instantiate at run time and pass some values in C++.Net. How can I acheive it? Please advice. Best, Sam
2
by: david | last post by:
Well, as a matter of fact I_HAD_MISSED a basic thing or two, anyway, although Ollie's answer makes perfectly sense when dealing with classes, it doesn't seem to me to apply as well if you have to...
2
by: FredC | last post by:
S Name Microsoft Windows XP Professional Version 5.1.2600 Service Pack 2 Build 2600 Total Physical Memory 1,024.00 MB MDE 2003 Version 7.1.3008 ..NET Framework 1.1 Version 1.1.4322 SP1...
2
by: active | last post by:
Because of an example I followed I've been instantiating Image objects. Now I notice that the documentation says the Image class is an abstract base class. Things seem to be working! Is the...
6
by: Gary Frank | last post by:
What are the ramifications if I were to instantiate an object tens of thousands of times and add them to an array? Or hundreds of thousands of times? Do you know if the act of instantiating a...
3
by: Nagesh | last post by:
hi, I have seen the winvnc(tightvnc server) source code in this I seen that class member funtions are calling without instantiating the object i.e. like vncService::ShowDefaultProperties() where...
5
by: Anders Borum | last post by:
Hello! Whilst refactoring an application, I was looking at optimizing a ModelFactory with generics. Unfortunately, the business objects created by the ModelFactory doesn't provide public...
3
by: Randy | last post by:
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...
7
by: john_smith_1221 | last post by:
Hello, I need to use the rand() function to generate a random value, I already know how to do it with srand(time(NULL)) and its "randomness" is sufficient for me, the problem is my code requires to...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.