Scope problem when filling a vector of base class pointers.

AI Thread Summary
The discussion centers on a programming challenge involving the calculation of impedance in an AC circuit with multiple components like resistors, capacitors, and inductors. The initial code fails because locally created objects go out of scope after the switch statement, resulting in an empty component library. The solution involves dynamically allocating memory for the components using the 'new' operator, which ensures that the objects persist beyond their initial scope. Participants emphasize the importance of proper memory management to avoid memory leaks, advising that any dynamically allocated components must be explicitly deleted when no longer needed. The final implementation successfully resolves the issue, allowing the program to function as intended.
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.
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...

Similar threads

Replies
5
Views
3K
Replies
75
Views
6K
Replies
6
Views
3K
Replies
21
Views
5K
Replies
49
Views
11K
Replies
3
Views
2K
Replies
2
Views
2K
Replies
14
Views
5K
Back
Top