[C++] Templates and inheritance
From: Pedro Graca (hexkid_at_hotpop.com)
Date: 09/28/04
- Next message: T.M. Sommers: "Re: Why is C still being used instead of C++"
- Previous message: Alwyn: "Re: ios::failbit always true"
- Next in thread: Thorsten Ottosen: "Re: [C++] Templates and inheritance"
- Reply: Thorsten Ottosen: "Re: [C++] Templates and inheritance"
- Reply: Alwyn: "Re: [C++] Templates and inheritance"
- Reply: Pedro Graca: "Re: [C++] Templates and inheritance -- SOLVED"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 28 Sep 2004 14:48:59 GMT
What am I missing?
[apart from the C++ books or a mentor :) -- books are in transit]
I'm trying to learn C++ and wanted to make a special stack that only
allows pushing values smaller than the current stack top.
My code compiles with
$ g++ -Wall ss.cpp -o ss
but gives a segmentation fault when run.
If it matters:
$ echo; g++ --version
g++ (GCC) 3.3.4 (Debian 1:3.3.4-12)
Copyright (C) 2003 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#include <iostream>
#include <exception>
#include <stack>
using namespace std;
template <class T>
class InheritedStack : public std::stack<T> {
public:
void my_push(const T& x) {
if (top() > x) {
push(x);
} else throw "Invalid push value";
}
};
/* ********* */
int main() {
stack<int> NS;
cout << "Normal stack: "; /* ********* */
NS.push(6); /* */
NS.push(9); /* STL stack */
NS.push(2); /* */
while (!NS.empty()) { /* works ok! */
cout << NS.top() << " "; /* */
NS.pop(); /* */
} /* ********* */
cout << endl;
cout << endl;
cout << endl;
/* ********* */
try {
InheritedStack<int> IS;
cout << "Inherited stack: ";
try {
IS.my_push(6);
IS.my_push(9); // error! -- change to 4
IS.my_push(2);
}
catch (char * msg) {
cerr << "Exception caught: " << msg << endl;
}
while (!IS.empty()) {
cout << IS.top() << " ";
IS.pop();
}
}
catch (std::exception& e) {
cerr << "Exception: " << e.what() << endl;
}
cout << endl;
}
-- USENET would be a better place if everybody read: | to email me: use | http://www.catb.org/~esr/faqs/smart-questions.html | my name in "To:" | http://www.netmeister.org/news/learn2quote2.html | header, textonly | http://www.expita.com/nomime.html | no attachments. |
- Next message: T.M. Sommers: "Re: Why is C still being used instead of C++"
- Previous message: Alwyn: "Re: ios::failbit always true"
- Next in thread: Thorsten Ottosen: "Re: [C++] Templates and inheritance"
- Reply: Thorsten Ottosen: "Re: [C++] Templates and inheritance"
- Reply: Alwyn: "Re: [C++] Templates and inheritance"
- Reply: Pedro Graca: "Re: [C++] Templates and inheritance -- SOLVED"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|