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

Pointer to Class prb

Hi All,

I tried the following code and it seems to work. I am really confused as to
how this is possible. Can someone please throw some light?

#include<iostream>
using namespace std;

class Y
{
public :
void foo()
{
cout << "Hello World"<< endl;

}
};

main ()
{
Y *ptr = NULL;
ptr->foo();
}

Thanks in advance.

Venky
Jul 22 '05 #1
8 1257

"Venkatesh" <hv********@yahoo.com> wrote in message
news:99**************************@posting.google.c om...
Hi All,

I tried the following code and it seems to work. I am really confused as to how this is possible. Can someone please throw some light?

#include<iostream>
using namespace std;

class Y
{
public :
void foo()
{
cout << "Hello World"<< endl;

}
};

main ()
{
Y *ptr = NULL;
ptr->foo();
}

Thanks in advance.

Venky


This code is dereferences a NULL pointer, therefore the program is wrong.

Now here is one of the secrets of C++. Almost always when a program does
something wrong like this, the C++ standard does NOT says that the program
must crash, its does NOT say that the program must produce an error message,
what it says is that the program has UNDEFINED BEHAVIOUR.

Undefined behaviour means exactly what it says, anything could happen,
including the program working. If you ran this program on a different
computer, or with a different compiler or even on a different day of the
week you might get different behaviour. This is what makes programming C++
hard.

John
Jul 22 '05 #2
Venkatesh wrote:
Hi All,

I tried the following code and it seems to work. I am really confused as to
how this is possible. Can someone please throw some light? main ()
{
Y *ptr = NULL;
ptr->foo();
}


This is called "dereferencing null." It's generally considered a bad
thing to do. Here's what I believe you want:

int main( )
{
Y y;
y.foo( );
}

If you really want a pointer, try this:

int main( )
{
Y y;
Y* p = &y;
p->foo( );
}
Jul 22 '05 #3
Venkatesh wrote in news:99**************************@posting.google.c om
in comp.lang.c++:
Hi All,

I tried the following code and it seems to work. I am really confused
as to how this is possible. Can someone please throw some light?

#include<iostream>
using namespace std;

class Y
{
public :
void foo()
{
cout << "Hello World"<< endl;

}
};

main ()
{
Y *ptr = NULL;
ptr->foo();
}


That the code "works", is one possible result of Undefined Behaviour.

Once you write ptr->something, when ptr is null, you are derefrencing
a NULL pointer, the C++ Standard no longer say's what behaviour your
code exhibits.

It "works", it "doesn't work", your computer grows legs and runs of
with the milkman, all are acceptable.

If your next question is "well why does it work on my implementation",
then probably (just guessing) ptr isn't need to actually call Y::foo(),
since it isn't virtual. So all that happens is ptr is passed to y::foo()
as the 'this' pointer and since Y::foo() doesn't reference 'this' in any
way you Get Away With It(tm).

FYI: main() returns int and only int, also all function's in C++
*must* have a return type, the K&R implicit int has *never* been C++.

HTH.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #4
Jeff Schwab wrote:
Venkatesh wrote:
Hi All,
I tried the following code and it seems to work. I am really confused
as to how this is possible. Can someone please throw some light?


main () {
Y *ptr = NULL;
ptr->foo();
}

This is called "dereferencing null." It's generally considered a bad
thing to do.


Sorry, I mis-read the question; you want to know why it *does* work. As
John and Rob already have mentioned, it's not guaranteed not to work.
Since the member function foo() in this case does not use its "this"
pointer for anything, this code is likely to work much of the time.
(Not that it's a good idea, y'unnastand.)
Jul 22 '05 #5
raj
hv********@yahoo.com (Venkatesh) wrote in message news:<99**************************@posting.google. com>...
Hi All,

I tried the following code and it seems to work. I am really confused as to
how this is possible. Can someone please throw some light?

#include<iostream>
using namespace std;

class Y
{
public :
void foo()
{
cout << "Hello World"<< endl;

}
};

main ()
{
Y *ptr = NULL;
ptr->foo();
}


c++ standard states that above code will lead to undefined behavior.
But most compilers will not crash untill you access a member variable
within the function.

If you try to modify a member variable of Y in this function, it would
crash on most platforms. Also if foo is declared virtual it would
crash while trying to find the virtual table of the null pointer.
Again this is not guaranteed, it is all undefined behavior.

Raj
Jul 22 '05 #6
hv********@yahoo.com (Venkatesh) wrote in message news:<99**************************@posting.google. com>...
Hi All,

I tried the following code and it seems to work. I am really confused as to
how this is possible. Can someone please throw some light?


You're derefencing a null pointer, which is undefined behavior.
Undefined behavior can do anything, including seeming to work.
--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 22 '05 #7
Venkatesh posted:
Hi All,

I tried the following code and it seems to work. I am really confused
as to how this is possible. Can someone please throw some light?

#include<iostream>
using namespace std;

class Y
{
public :
void foo()
{
cout << "Hello World"<< endl;

}
};

main ()
{
Y *ptr = NULL;
ptr->foo();
}

Thanks in advance.

Venky

You must realize that "foo" is just like any other function. It is in memory
and it has an address in memory. It may be something like this:

void foo(MyClass* this)
{

cout << "Hello World"<< endl;
}
When you declare that "ptr" pointer and then use it call "foo", you are
calling the "foo" function as so:

foo(AnyNumber); //You didn't intialize "ptr" so it can contain ANY value,
although most likely 0.

So now when "foo" is called, it _does_ work because it doesn't even _look_
at the bogus pointer value. But...

void foo(MyClass* this)
{
cout << "Hello World"<< endl;

this.memberVariable = 5;
}
This most certainly will crash... I hope is does in anyway if you're running
an in-any-way-decent Operating System.
Just to throw it in there: "foo" should be declared "static".
That said, and as about 20,000 peole have said already, what you're doing
is...

undefined


-JKop
Jul 22 '05 #8
Venkatesh wrote:
class Y
{
public :
void foo()
{
cout << "Hello World"<< endl;

}
};

main ()
{
Y *ptr = NULL;
ptr->foo();
}

First off what Jerry Coffin said is true; you're just lucky that it worked.

As for why it works this is *probably* what happened. Using a pointer
to call a member function really didn't deference the pointer but
instead the function was called with the pointer as a hidden parameter
that inside foo becomes the this pointer. So the call "ptr->foo()"
probably got translated into something like "Y_foo(ptr)". Inside foo
the value of "this" was null but you never used it for anything and so
no problems.

And thus your program seems to work.

Try adding this code to foo:

if (this == 0)
cout << "Uh oh, this was null! I'm lucky the compiler doesn't slap
me or something" << endl;
Jul 22 '05 #9

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

Similar topics

2
by: lawrence | last post by:
I had some code that worked fine for several weeks, and then yesterday it stopped working. I'm not sure what I did. Nor can I make out why it isn't working. I'm running a query that should return 3...
5
by: lawrence | last post by:
I posted before, but have now narrowed my problem down to this method. At the start of the method, I test to make sure that I have a resource, a pointer to data returned from a database. This test...
2
by: Asfand Yar Qazi | last post by:
Hello. Partly for learning purposes, I have written a smart pointer class. Could you please tell me what's wrong with it? (I know there's something wrong with it, but just not what!) Note...
4
by: Carsten Spieß | last post by:
Hello all, i have a problem with a template constructor I reduced my code to the following (compiled with gcc 2.7.2) to show my problem: // a base class class Base{}; // two derived...
6
by: Itay_k | last post by:
Hello, I want a member in my class that will save pointer to pointer to System::Drawing::Image class. When I write on my class code: System::Drawing::Image **bmp; I get this error message:...
2
weaknessforcats
by: weaknessforcats | last post by:
Handle Classes Handle classes, also called Envelope or Cheshire Cat classes, are part of the Bridge design pattern. The objective of the Bridge pattern is to separate the abstraction from the...
7
by: WaterWalk | last post by:
Hello. I thought I understood member function pointers, but in fact I don't. Consider the following example: class Base { public: virtual ~Base() {} }; class Derived : public Base {
5
by: Tim Frink | last post by:
Hi, I'm experimenting with function pointers and found two questions. Let's assume this code: 1 #include <iostream> 2 class A; 3 4 //////////////////////////////////////////// 5 class B
5
by: Immortal Nephi | last post by:
I would like to design an object using class. How can this class contain 10 member functions. Put 10 member functions into member function pointer array. One member function uses switch to call...
8
by: mathieu | last post by:
Hi there I have implemented a very simple smartpointer class (invasive design). And I was wondering what should be the natural API when using those in a Container. I choose to define the...
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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:
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?
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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
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,...

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.