473,396 Members | 1,804 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,396 software developers and data experts.

Why the constructor is not called in this case?

bajajv
152 100+
Hi,
I made a class A and a class B. Then created an object of class A using a pointer of A.
Then I gave ->
B* bptr = (B*) aptr;
When I call functions of class B using the bptr, it calls the function.
But during the whole execution, it never calls the constructor of type B.
Then how can it call the function from B class?
What is the mechanism behind this?
How is the variable in class B initialized with some value in class A? And since it is calling functions and initializing variable in class B, it should have constructed an object of this class?? (am I right...?)

Expand|Select|Wrap|Line Numbers
  1. class A{
  2. public: 
  3.     int j;
  4.     A() 
  5.     {
  6.         printf("Inside A constructor.\n");
  7.         j=20;
  8.     } 
  9.     ~A() {}
  10. };
  11.  
  12. class B{
  13. public:
  14.     int i;
  15.     int k;
  16.     char c;
  17.     B() {printf("Inside B default constructor.\n");}
  18.     B(A a)
  19.     {
  20.         printf("Inside B constructor.\n"); 
  21.         c='c';
  22.         i = 10; 
  23.         k=100;
  24.     } 
  25.     ~B(){} 
  26.     void fun()
  27.     {
  28.         printf("Inside fun\n");
  29.         printf("i = %d\n", i);
  30.         printf("k = %d\n", k);
  31.     }
  32. };
  33.  
  34. int main()
  35. {
  36.     A* aptr = new A();
  37.     B* bptr = (B*) aptr;
  38.  
  39.     bptr->fun();
  40.  
  41.     return 0;
  42. }
  43.  
Apr 16 '11 #1
4 2188
johny10151981
1,059 1GB
you never created any object of class B that is why no construction has been called
Apr 17 '11 #2
Banfa
9,065 Expert Mod 8TB
You problem is that you are mixing C and C++ code.

You are using printf when you should be using cout and you use a C style cast

Expand|Select|Wrap|Line Numbers
  1.     B* bptr = (B*) aptr;
  2.  
The problem with C style casts is that they just work without actually verifying if the cast is sensible and possible. You should avoid using C style casts in favour of one of the C++ casts
static_cast
dynamic_cast
const_cast
reinterpret_cast
Good C++ code has little need to cast so a proliferation of casts in your code would suggest a design flaw.

If you do need to cast then you should be using static_cast as your default using the other ones where you have a good reason to.

dynamic_cast is probably the next most used type used where you can not know the actual type of the object until run-time, you should always check the return value of a dynamic_cast to make sure it is not NULL which it will be if the requested cast was not valid.

const_cast is just for changing the const and volatile specifiers of a type and I have never had cause to use it.

reinterpret_cast is the most dangerous, equivalent to the old C style cast, the compiler just assumes the programmer knows what they are doing and copies the pointer value with no interpretation. I have had call to use this but generally only when dealing with a C API some of which require passing a pointer to object A as a pointer to object B.

In this case you should have used static_cast and if you had done so you would have got the compiler error

error: invalid static_cast from type 'A*' to type 'B*'

That is A* and B* are not compatible types and you can't just copy one to the other.
Apr 18 '11 #3
bajajv
152 100+
Thanks Banfa, your reply was helpfull.

But my doubt is that in the code, I am printing values of variables, which are not static. So, how come I am able to print their values, when I am actually not creating any object?

Because, I think that the non-static variables of a class come into existance only when the object is created.
Apr 20 '11 #4
Banfa
9,065 Expert Mod 8TB
It doesn't matter whether you created an object or not, you copied a value into a pointer to type B in a way that circumvents any checks the compiler might usually do.

Like I said at this point the compiler just assumes you know what you are doing, you said "this memory address is the address of an object of type B" and the compiler replied with "OK if you say so" and then the compiler proceeded to act as if that memory location contained an object of type B even though it didn't. B::i is likely to have had the same value as A::j since that memory actually contains an object of type A, B::k and B::c will likely just have random values although actually accessing the would be undefined behaviour since those bits of memory would be outside the bounds on the object of type A that you actually allocated.
Apr 21 '11 #5

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

Similar topics

9
by: djskrill | last post by:
Why is the Constructor called 4 times but the Destructor 5 times? I am using MS VC 6. If this has been covered already please let me know. The Code: #include <stdio.h> class MyClass {...
5
by: TechCrazy | last post by:
I am compiling like g++ -O0 MyString.cpp Should the copy cnstrs be called thrice? Any optimization going on here? -------------------------- #include <iostream> #include <string>
3
by: Alexander Stippler | last post by:
Given the following code snippet we get some unexpected behaviour: //-------------------------------------------------------------------- #include <iostream> using namespace std; struct A {...
10
by: ios | last post by:
Hi Can someone tell me what is different between below case? strcpy(eventname, "MDCX_RSP"); and sprintf(eventname, "MDCX_RSP"); Thanks, Leon
7
by: gyan | last post by:
follwing code gives error: 1 #include<iostream.h> 2 int main() 3 { 4 int a=5,b; 5 switch(a){ 6 case 1: 7 {b=5; 8 break; 9 }
9
by: janzon | last post by:
Consider the code below. The output is the following two lines: 0xbfc78090 0xbfc780a0 This proves that the variable m in main() is not the very same instance of MyClass as temp_m in hello()....
2
by: 440gtx | last post by:
I have a class that maintains a static std::list of its instances. Thus, due to the order of constructors ambiguity of itself and std::list, it cannot be safely instantiated until after main is...
4
by: George2 | last post by:
Hello everyone, Why visual studio does not optimize constructor in this case? I do not understand what the MSDN mentioned, if use different named object, compiler can not optimize. Why? ...
7
by: * Tong * | last post by:
Hi, I couldn't figure out how to properly type cast in this case: $ cat -n type_cast.c 1 #include <stdio.h> 2 3 typedef unsigned char Byte; 4 typedef signed char Small_Int; 5
5
by: Juha Nieminen | last post by:
Let's assume we have a class like this: //--------------------------------------------------------- #include <iostream> class MyClass { public: MyClass() { std::cout << "constructor\n"; }...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...
0
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...
0
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,...

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.