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

Accessing a private data member from a separate source file to a header file

Hi all new to this forum, just thought i'd post in here because i am having a bit of trouble with an assignment... basically i have this class in a header file called Product.h...

class Product
{
private:
	int _id;
	unsigned int _price;
public:

};


I access this code a lot as i have an array of products in my main.cpp but we had to change this from a struct to this so i have done so and had to create a new source file (product.cpp) for the get and set functions but i am having a bit of trouble in how to do this i include the Product.h but then as for the functions i do not know where to start! Thanks

Reeseoo
Newbie Poster
5 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
 

Just how you would do this will depend on the compiler (and IDE) you are using, but in general, you would need to set up a Project (or a Makefile, for compiling from the command line) that would keep track of which files need to be compiled and linked into the executable file. Could you tell us how you are compiling this, and with what compiler and editor?

If you need to review the concepts behind linker and why you don't want to use #include for the code files, you might want to see this post for a somewhat whimsical explanation of inclusion and linking.

Schol-R-LEA
Posting Pro
556 posts since Oct 2010
Reputation Points: 254
Solved Threads: 85
 

The compiler i am using is Visual C++ 2008 and they are all linked in a project and all the headers are included as should be , I have made a function in product.cpp with the prototype in product.h which is a

friend int


, would that work? but i would have to implement functions into functions to access the data!

Reeseoo
Newbie Poster
5 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
 

Well you just need to declare your functions in your class.

#ifndef MYCLASS_H
#define MYCLASS_H

class MyClass
{
	private :

		int value;
		float value_float;
		void foo (); // private function of this class 
	
	public :
		
		// constructors
		MyClass ();
		MyClass ( const int& );

		//public functions of your class		
		void func_1 ();
		int getValue ();				
};
#endif // MYCLASS_H


Now in your cpp file, you can define your functions.

int MyClass::getValue ()
{
	return value;
}

This might helps. Hope I did not misunderstood you. Sorry if I did.

LRRR
Junior Poster in Training
55 posts since Dec 2011
Reputation Points: 22
Solved Threads: 15
 

Yeah this works thank you :)

Reeseoo
Newbie Poster
5 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: