Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++
Hello .. !!
Hope You All Are At Good State Of Health.. !! Smile | :)
 
Sir I'm little puzzled with my code, I'm confused in calling public functions in main .. what should be entered there .. Moreover I should write a destructor to avoid Memory Leak,, :/ ??
Can You Please Elaborate With A Similar Example For More Clarification ..
 
Thank you for your consideration ..
 
#include <iostream>

 
using namespace std;
 
class Object
{
private:
 
	int size;
	int *array;
 
public:
 
	void setdata(int, int );
	void getdata(int, int );
	void search(int, int );
	void bubble(int, int );
	Object(int size)
	{
		//this->size = size;
		array = new int[size];
	}
};
 

void setdata(int array[], int size)
{
	cout << "==> Entering Data <==" << endl;
	for (int i = 0; i < size; i++)
	{
		cout << ">> Enter Element #" << i+1 << ": ";
		cin >> array[i];
	}
}
 
void getdata(int array[], int size)
{
	cout << "==> Printing Data <==" << endl;
	for (int i = 0; i < size; i++)
	{
		cout << array[i] << " ,";
	}
	cout << "\n";
}
 
void search(int array[], int size)
{
		int key;
		cout << "Please Enter A KEY To Find: ";
		cin >> key;
		int index = 0;
		bool found = false;
		for (int i = 0; i < size; i++)
		{
			if ( (!found) && key == array[i])
			{
				index = i;
				found = true;
			}
		}
		if (found)
			{
				cout << "K E Y Found At The Index: " << index+1 << endl;
			}
		else
		{
			cout << "K E Y is not present." << endl;
		}
		cout << '\n' << endl;
}
 
void bubble(int array[], int size)
{
	int temp;
	for (int i = 1; i < size; i++)
	{
		for (int j = 0; j < size; j++)
		{
			if (array[j] > array[j+1])
			{
				temp = array[j];
				array[j] = array[j+1];
				array[j+1] = temp;
			}
		}
	}
}
 
int main()
{
	const int size = 5;
	const int array[size];
	Object u(size);
	u.setdata(array, size); // ?? 
	u.getdata();
	u.search();
	u.bubble();
	system("pause");
	return 0;
}
Posted 29-Apr-13 12:51pm
ctype.h1.7K
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

I'm puzzled by your code too. It won't compile. The method declarations and definitions don't match. The parameter lists "(int, int)" and "(int array[], int)" need to be the same. You haven't used very good names for the methods. Yes, you should include a destructor which deletes the memory managed array.
 
Your code needs a lot of work, and I don't really understand the rest of your question...
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

As a sort of exercise for myself and hoping that this will help you learn, I've had a go at "fixing" your code, including a few comments regarding coding standards and the like.
 
However, I would stress that I would not expect to see code like this in any professional project, which I think at least one of my comments should make clear.
 
Regards,
Ian.
 
#include <iostream>

// Personally, I don't recommend "using" the std namespace, certainly not in a complex program,
// as the namespace contains a large number of classes and templates, etc, and the chance of name clashes is greater,
// and it also hides where functions are defined.  I've left this for this simple program, but I'd rather have to
// type "std::cout" or "std::vector" etc, then include this.  Besides, the typing is in many cases descreased by
// intellisense, since you merely need to type std:: and you get a list of included functions and classes, etc.
using namespace std;
 

// Class name should be descriptive of what the object represents.  The "type" of object.
// In this case, this looks like you're implementing a raw array (for some reason),
// so I've gone with this name, although I don't really like it.
// Ideally if you were going to do this for real, you would probably make this into a
// template class, so that you could specify what type of array it is.
// Oh!  The STL already has some neat template classes... why not use one of them?
//  Eg. std::vector<int>.
class IntArray
{
	public:
		// Note that the coding standards you use will determine the casing for class, variable and method names.
		// The most prominent, and in my view best standards, recommend Pascal casing for class and method names,
		// and camel casing for local and member variables.
		void SetData();
		void GetData() const;  // Declare methods const when they don't modify the class (i.e. they don't change the member variables)
		void Search() const;
		void Bubble();  // Although it technically doesn't modify the class (because it doesn't change the pointer, but changes the data pointed to), the design of this class implies that it is changing the class, and fundamentally it is modifying the data after all.  With a different implementation this might be important, so for the sake of the caller, this is not declared const.  (It is similar for SetData in this example).

		IntArray
			(
			int size
			)
		{
			this->size = size;
			values = new int[size];
		}
 
		// Use a destructor to free any memory allocated by the object.
		// Always declare your destructor as virtual.
		virtual ~IntArray()
		{
			delete [] values;
		}
 
	private:
		// The compiler will generate a copy and assignment constructor automatically, unless you define them yourself.
		// Since you are allocating memory that would need to be correctly copied, you need to handle this (the default action would be to
		// copy the pointer, which you probably don't want as that will cause problems when you free the memory, unless
		// you also implement some kind of reference counting).
		// However, instead, here I simply declare the constructors (private so they can't be called) and then never implement them.
		// This means the class cannot be copied - if some code tries to there will be a compiler error.  In that case only
		// decide whether you really need to copy the object and implement the constructors accordingly to copy the memory into the new object.
		IntArray
    			(
			const IntArray&			other
			);
		IntArray&	operator=
			(
			const IntArray&			other
			);
		// Some compilers may also automatically generate a default constructor.
		// Whether it would or not, no harm in declaring it privately here, so that it doesn't, and then again just not implementing it, to force someone using the class to specify the size.
		IntArray();
 
	private:
		int size;
		int* values;  // "array" is a reserved word in VC++.
};
 
// Here are your methods, which now belong to the class.

// Note: I have largely left these as you had them, but I don't necessarily agree with what you are doing in them!
// I don't think a class like this should be using cin and cout.  The data should be obtained elsewhere and then set into the object.
// Apart from anything else, it means you've ended up with some commonly named methods, "Set" and "Get", but where the "Set" method takes
// no parameters, and the "Get" method returns nothing.  Both of these scenarios is very odd.
// As they stand these methods might be better named "InputData" (instead of SetData) and "OutputData" (instead of GetData).

void IntArray::SetData()
{
	cout << "==> Entering Data <==" << endl;
 
	// Always use the prefix increment operators (++, --) except when absolutely necessary.
	// I.e. only use the postfix operators when you're performing some other operation on the
	// variable which you wish to be carried out first.  Even then, you should probably try not
	// to use them as that can cause difficult read code.  Generally, it is best to only use the
	// increment operators in a statement on their own, such as one of the statements in a for loop.
	// Then, on one level it doesn't matter whether you use the postfix or the prefix operators,
	// except that the prefix operator creates one less machine code step.  To explain:
	// "++i" means "increment i and then return the value of i".  In other words, it's equivalent to: "i = i + 1; return i;"
	// "i++" means, "return the value of i, and then increment i by one".  It's more like writing "temp = i; i = i + 1; return temp;"
	// When the return value isn't being used, so the end result of using either would be the same, favour the prefix version.

	for (int i = 0; i < size; ++i)
	{
		cout << ">> Enter Element #" << i+1 << ": ";
		cin >> values[i];
	}
}
 
void IntArray::GetData() const
{
	cout << "==> Printing Data <==" << endl;
	for (int i = 0; i < size; ++i)
	{
		cout << values[i] << " ,";
	}
	cout << "\n";
}
 
void IntArray::Search() const
{
	int key;
	cout << "Please Enter A KEY To Find: ";
	cin >> key;
	int index = 0;
	bool found = false;
	for (int i = 0; i < size; ++i)
	{
		if ((!found) && (key == values[i]))
		{
			index = i;
			found = true;
		}
	}
	if (found)
	{
		cout << "KEY Found At The Index: " << index+1 << endl;
	}
	else
	{
		cout << "KEY is not present." << endl;
	}
	cout << '\n' << endl;
}
 
void IntArray::Bubble()
{
	for (int i = 1; i < size; ++i)
	{
		for (int j = 0; j < size; ++j)
		{
			// I THINK this is the algorithm you wanted here, but I'm not sure...  There are of course different ways to do a bubble sort.
			if (values[j] > values[i])
			{
				int temp = values[j];
				values[j] = values[i];
				values[i] = temp;
			}
		}
	}
}
 
int main()
{
	const int size = 5;
	IntArray u(size);
	u.SetData();
	u.GetData();
	u.Search();
	u.Bubble();
	u.GetData();
	system("pause");
	return 0;
}
  Permalink  
v3
Comments
H.Brydon at 30-Apr-13 0:00am
   
Valiant effort, but I think you are trying too hard. This looks suspiciously like homework for a student (or code that somebody needs a lot more help than you can provide). Doing homework for someone doesn't really help anybody.
 
+5 for the effort.
Nerdy Usman at 30-Apr-13 0:09am
   
Great ..
But at least I give a try ..
This is just for my practice ..
I've to use constructor and destructor .. Don't want to use static main ..
Thank You Ian A Davidson .. +5
Nerdy Usman at 30-Apr-13 0:22am
   
I'm a student sir not professional ..
Now i'm going to college .. I will update the code asap ;)
Nerdy Usman at 30-Apr-13 13:38pm
   
Sir with you kind support .. I've updated the code .. please have an eye .. !!!!
H.Brydon at 30-Apr-13 21:30pm
   
Also, Bubble() shouldn't be const. I think the compiler will complain about this too.
Ian A Davidson at 1-May-13 2:34am
   
That is a good point though: for the sake of the person using the code it probably shouldn't be const because it is modifying the data of the class.
But technically, the class member is a pointer, so by declaring the method const, the pointer becomes const and the function cannot change it, which it doesn't. It doesn't prevent the method modifying the content of what the pointer points to! So actually no the compiler doesn't complain.
 
If the implementation was different it might matter; so for that reason I think I would agree with you in this case.
It's an interesting example of good OO design versus programming language behaviour.
 
I'll update my example with your recommendation.
Thanks for that.
Regards,
Ian.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

The code uses the samne variable name for class member and parameters function which is a bad practice in general case (it is acceptable for special cases like constructors). Same for size member.
 
array should not be used as a variable name as it look too much like a predefined name as many language has that word predefined.
 
You don't really have to manage memory as it is allocated on stack. You should remove class members as they are not used. In such a case,the class function should probably be static. In that case, the constructor should not allocate memory.
 
Alternatively, it would be possible that allocation would be done Inside the class and in such case, your function won't have any parameters and it would be necessary to provide a destructor (and also a copy constructor and an assignment operator).
 
Finally, Object is really a bad class name. First it means nothing and second, this is a name already widely used in language as C# as a base class of all objects.
 
As mentionned in another solution,m there is a lot of problem in your code and should first learn the langage by reading some book.
  Permalink  
Comments
H.Brydon at 30-Apr-13 0:05am
   
I agree with your comments about names and naming but I don't follow your logic about memory management and things on the stack.
 
OP fumbled this a bit but there can be a useful purpose for a class containing an array (with different names), where the data is allocated on the heap. The size should be stored as well in the constructor (instead of ignoring it and passing it into all methods).
Philippe Mori at 30-Apr-13 8:27am
   
If we assumes that all free functions like setdata were intented to be members of the class Object, then it is clear that there is no need to have both members and parameters for the array. Generally, the one that allocate the memory is the one that should release it (and otherwise it is recommanded to use appropriate smart pointers).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 350
1 Jochen Arndt 150
2 Richard MacCutchan 135
3 Andreas Gieriet 100
4 DamithSL 95
0 OriginalGriff 6,045
1 DamithSL 4,601
2 Maciej Los 4,087
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,260


Advertise | Privacy | Mobile
Web04 | 2.8.141220.1 | Last Updated 1 May 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100