Scope problem when filling a vector of base class pointers.

Click For Summary

Discussion Overview

The discussion revolves around a programming issue related to managing a vector of base class pointers in C++. Participants explore how to properly store dynamically created objects of derived classes (resistors, capacitors, inductors) in a vector without losing them when they go out of scope.

Discussion Character

  • Technical explanation
  • Conceptual clarification
  • Debate/contested

Main Points Raised

  • One participant describes a problem where a resistor object goes out of scope after being created within a switch statement, leading to a failure when trying to access it later.
  • Another participant suggests using dynamic memory allocation with 'new' to create the resistor object, which would prevent it from disappearing when the scope ends.
  • A further suggestion is made to directly push the dynamically allocated resistor into the vector, eliminating the need for an intermediate pointer variable.
  • Concerns are raised about memory management, specifically the need to delete dynamically allocated objects to avoid memory leaks when they are no longer needed.

Areas of Agreement / Disagreement

Participants generally agree on the necessity of dynamic memory allocation to solve the scope issue, but there is an emphasis on the importance of careful memory management, indicating a shared concern about potential pitfalls.

Contextual Notes

Participants do not delve into specific implementations of memory management practices or the implications of using smart pointers, which could further influence the discussion.

Who May Find This Useful

This discussion may be useful for programmers dealing with object-oriented design in C++, particularly those facing challenges with scope and memory management in dynamic object creation.

JesseC
Messages
247
Reaction score
2
I'm trying to write a simple program to calculate the impedance of an AC circuit consisting of an arbitrary number of resistors, capacitors and inductors combined in series or parallel. First I ask the user to create the components they wish to use in the circuit, and this is where I hit the problem:

Code:
	cout<< endl 
		<< "Please create the components you wish to use." << endl
		<< "Enter R for a resistor, C for a capacitor, I for" << endl
		<< "an inductor or enter 'S' to stop creating components." << endl;

	char componentType;
	cin >> componentType;

	// vector of base class pointers to store the components
	vector <component*> componentLibrary;

	switch(componentType)
	{
	case 'r':
	case 'R':
		{
		cout << "What is the resistance of the resistor in ohms?" << endl;
		double tempResistance;
		cin >> tempResistance;
                // create resistor according to user input
		resistor R(tempResistance);
		// place resistor in component library
		componentLibrary.push_back(&R);

		break;
		}
	case 'c':
	case 'C':
		{
			cout << "What is the capacitance in farads?" << endl;
		...
                ... etc
	}

	
	
	cout << "Test Output:" << endl;
	cout << componentLibrary[0]->getImpedance() << endl; // code fails here.

I know why this code fails, because the resistor object goes out of scope when the switch statement ends so the component library doesn't contain anything...

what I'm not sure about is how to get around this in a simple way?? I would hit the same problem with IF statements...
 
Technology news on Phys.org
I assume resistor is a class derived from a base class component. Instead of
Code:
resistor R(tempResistance);
you want
Code:
component* p = new resistor(tempResistance);

(Later on you'll need something to delete the components).
 
Allocate the resistor object dynamically using 'new'. Then it won't disappear on you automatically at the end of scope.

Code:
resistor *resistorPtr = new resistor(tempResistance);
componentLibrary.push_back(resistorPtr);

I think you can combine these steps and eliminate the pointer variable:

Code:
componentLibrary.push_back(new resistor(tempResistance));

You need to be very careful about memory management with this technique, though. If you ever want to "throw away" a component, you need to explicitly release the memory that it uses. For example, if you need to remove a component from the "library", without putting the component somewhere else:

Code:
delete componentLibrary[k];  // Releases the memory that componentLibrary[k] points to.
// Next, do whatever you do that removes the pointer itself from the vector.

Otherwise you have a "memory leak." The now-inaccessible memory chunk consumes some of your memory space until the program finishes, at which point the program's entire memory space reverts back to the operating system.
 
Last edited:
Thanks for the help! Working fine now.
 

Similar threads

  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 3 ·
Replies
3
Views
4K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 6 ·
Replies
6
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 4 ·
Replies
4
Views
5K
Replies
1
Views
3K
  • · Replies 49 ·
2
Replies
49
Views
12K
  • · Replies 75 ·
3
Replies
75
Views
7K