954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Passing data in constructors

I have two files sampleclass.cpp and sampledataclass.cpp along with sampleclass.h and sampledataclass.h

In sampleclass.cpp in the constructor I give a value to a variable

sampleclass.cpp
sampleclass:sampleclass(){
x = "some string value";
}

In sampleclass.h I create x and an instance of the data class
sampleclass.h
CString x;
sampledataclass myDC;

Now in the constructor of the data class I want to be able to set the value of another string to the value of x
sampledataclass.cpp
sampledataclass:sampledataclass(){
CString y = mysampleclass->x;
}

The h file has this
sampleclass.h
sampleclass *mysampleclass;

How do I do this without getting a runtime error

kinger29
Light Poster
36 posts since Mar 2008
Reputation Points: 11
Solved Threads: 2
 

Never define global variables in .h files! You can declare these variables, of course - simply use extern keyword before its type, but define such variables in one and only only cpp file.
As usually, there are better solutions than global variables using, but it's the other story.

The key question in your case: who (and when) must initialize (global?) mysampleclass pointer variable? I don't know the answer because your snippet is too laconic.

It seems you have too cumbersom mechanics for a simple task. May be you present more codes and better your program case description?

ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You