473,549 Members | 3,048 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

using new in functions, pointers passed still NULL after called?!

Hello,

So I think the answer to this question is going to be rather simple.

Basically I have a pointer to a class, and I want to have a function
to call to initialize it.

After this function is called, the pointer is still NULL.

Here is a simplified version, but basically the same:

void main(){
MyClass *ptr = NULL;
createMyClass(p tr);
}

createMyClass(M yClass *ptrToClass){
ptrToClass= new MyClass();
}

Any reason why ptr would still be NULL after createMyClass is called?

Thanks,
_ivan
Jul 19 '05 #1
4 4519
Hi Ivan,

"_ivan" <ik***@nyu.ed u> wrote in message
news:f4******** *************** ***@posting.goo gle.com...
| void main(){
| MyClass *ptr = NULL;
| createMyClass(p tr);
| }
|
| createMyClass(M yClass *ptrToClass){
| ptrToClass= new MyClass();
| }
|
| Any reason why ptr would still be NULL after createMyClass is called?

By default in C/C++, function parameters *copies* of values
that are passed.

In the code above, changing the value of 'ptrToClass' will
not affect 'ptr' in main.

A way to achieve what you expect is to pass the parameter
by reference. What you need to do is change the function's
signature as follows:
createMyClass( MyClass*& ptrToClass )

This will behave as you expect...
hth
--
http://www.post1.com/~ivec <> Ivan Vecerina
http://www.brainbench.com <> Brainbench MVP for C++
Jul 19 '05 #2

_ivan <ik***@nyu.ed u> wrote in message
news:f4******** *************** ***@posting.goo gle.com...
Hello,

So I think the answer to this question is going to be rather simple.

Basically I have a pointer to a class, and I want to have a function
to call to initialize it.
A class type object should be initialized with a
constructor, not by calling a function after the fact.

After this function is called, the pointer is still NULL.

Here is a simplified version, but basically the same:

void main(){
int main() {
MyClass *ptr = NULL;
createMyClass(p tr);
}

createMyClass(M yClass *ptrToClass){
ptrToClass= new MyClass();
}

Any reason why ptr would still be NULL after createMyClass is called?
Yes. Look up 'pass by value' vs. 'pass by reference'.

#include <iostream>

class MyClass {};

void createMyClass(M yClass *&ptrToClass)
{
ptrToClass = new MyClass;
}

int main()
{
MyClass *ptr = 0;
std::cout << "Before: " << ptr << '\n';
createMyClass(p tr);
std::cout << "After : " << ptr << '\n';
delete ptr;
return 0;
}

But why not just create the object directly in main(),
and don't fool with 'new'.?

int main()
{
MyClass mc;
return 0;
}

Or if you must use 'new' for whatever reason, why not
just call it directly instead of making a separate
function?

int main()
{
MyClass *ptr = new MyClass;
/* etc */
delete ptr;
return 0;
}

-Mike
_ivan

Jul 19 '05 #3

"Ivan Vecerina" <iv**@myrealbox .com> wrote in message news:3f******** @news.swissonli ne.ch...
By default in C/C++, function parameters *copies* of values
that are passed.

With the exception of the apparent (but not in reality) passing of arrays.
Jul 19 '05 #4
"Mike Wahler" <mk******@mkwah ler.net> wrote in message news:<y1******* *******@newsrea d3.news.pas.ear thlink.net>...
_ivan <ik***@nyu.ed u> wrote in message
news:f4******** *************** ***@posting.goo gle.com...
Hello,

So I think the answer to this question is going to be rather simple.

Basically I have a pointer to a class, and I want to have a function
to call to initialize it.


A class type object should be initialized with a
constructor, not by calling a function after the fact.

After this function is called, the pointer is still NULL.

Here is a simplified version, but basically the same:

void main(){


int main() {
MyClass *ptr = NULL;
createMyClass(p tr);
}

createMyClass(M yClass *ptrToClass){
ptrToClass= new MyClass();
}

Any reason why ptr would still be NULL after createMyClass is called?


Yes. Look up 'pass by value' vs. 'pass by reference'.

#include <iostream>

class MyClass {};

void createMyClass(M yClass *&ptrToClass)
{
ptrToClass = new MyClass;
}

int main()
{
MyClass *ptr = 0;
std::cout << "Before: " << ptr << '\n';
createMyClass(p tr);
std::cout << "After : " << ptr << '\n';
delete ptr;
return 0;
}

But why not just create the object directly in main(),
and don't fool with 'new'.?

int main()
{
MyClass mc;
return 0;
}

Or if you must use 'new' for whatever reason, why not
just call it directly instead of making a separate
function?

int main()
{
MyClass *ptr = new MyClass;
/* etc */
delete ptr;
return 0;
}

-Mike
_ivan

You can also use the pointer to pointer like this
#include <iostream>
class MyClass
{
};

void createMyClass(M yClass **ptrToClass)
{
*ptrToClass= new MyClass();
std::cout<<"Val ue in Function:"<<*pt rToClass<<std:: endl;
}
int main()
{
MyClass *ptr = NULL;
createMyClass(& ptr);
std::cout<<"Val ue in main:"<<ptr<<st d::endl;
return 0;
}
in this way change reflects in the actual pointer when you return from the function.
Jul 19 '05 #5

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

Similar topics

7
5168
by: Mike D. | last post by:
I have a problem with a dynamic library I am developing, but it is really more of a pointer issue than anything else. Hopefully someone here can lend me some assistance or insight into resolving this. Ok... here goes.... I have a function that passes a pointer to a string to another function. For example: int FunctionA ()
27
4713
by: MK | last post by:
I am a newbie. Please help. The following warning is issued by gcc-3.2.2 compiler (pc Linux): ================================================================== read_raw_data.c:51: warning: assignment makes pointer from integer without a cast ================================================================== when the following piece of...
9
5046
by: Mikhail Teterin | last post by:
Hello! I'd like to have a variable of a pointer-to-function type. The two possible values are of type (*)(FILE *) and (*)(void *). For example: getter = straight ? fgetc : gzgetc; nextchar = getter(file); What type should I give to `getter' so that the compiler does not issue
19
4230
by: Ross A. Finlayson | last post by:
Hi, I hope you can help me understand the varargs facility. Say I am programming in ISO C including stdarg.h and I declare a function as so: void log_printf(const char* logfilename, const char* formatter, ...); Then, I want to call it as so:
7
6223
by: srinivasaraokoneru | last post by:
Can structures be passed to the functions by value?
47
3839
by: Albert | last post by:
So structures are useful to group variables, so you can to refer to a collection as a single entity. Wouldn't it be useful to also have the ability to collect variable and functions? Ask K&R say, C programs consist of variables to store the input and functions to manipulate them. This would make C object-oriented - how cool would that be?...
29
3627
by: shuisheng | last post by:
Dear All, The problem of choosing pointer or reference is always confusing me. Would you please give me some suggestion on it. I appreciate your kind help. For example, I'd like to convert a string to a integer number. bool Convert(const string& str, int* pData); bool Convert(const string& str, int& data);
221
367123
Atli
by: Atli | last post by:
You may be wondering why you would want to put your files “into” the database, rather than just onto the file-system. Well, most of the time, you wouldn’t. In situations where your PHP application needs to store entire files, the preferred method is to save the file onto the server’s file-system, and store the physical location of the file in...
68
4564
by: Jim Langston | last post by:
I remember there was a thread a while back that was talking about using the return value of a function as a reference where I had thought the reference would become invalidated because it was a temporary but it was stated that it would not. This has come up in an irc channel but I can not find the original thread, nor can I get any code to...
0
7446
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7718
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7956
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
7470
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
7809
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
6041
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
3498
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...
1
1058
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
763
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.