I have an abstract class and some others that derive from it. The abstract class has only two methods that I don't need to override. (My implementations only add to the abstract class). I currently have a dummy function inside my abstract class just to make it abstract. Here's my code:
(My questions are at the end)
/**
* Interface that defines the Tag/Word objects found in the HTML
*/
class HTMLElement{
public:
/**
* Constructor
* @param v Value
* @param t Type (Word/Tag/Etc...)
*/
HTMLElement(string& v, int t);
virtualint getType();
virtual string getValue();
conststaticenum ElementType { TAG = 1, WORD} elementType;
protected:
string value;
int type;
private:
/**
* To make this class an abstract class
*/
virtualvoid test() = 0;
// void setValue(string& v);
};
HTMLElement.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
HTMLElement::HTMLElement(string& v, int t) : value(v), type(t) {
return;
}
int HTMLElement::getType() {
return type;
}
string HTMLElement::getValue() {
return value;
}
//void HTMLElement::setValue(string& v){
// value = v;
//}
Word.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class Word :public HTMLElement {
public:
/**
* Constructor. Initializes the value of the word and the URL where it was found.
*/
Word(string v, URL u);
/**
* Get's the URL where the word was found
*/
string &getURL();
private:
URL url;
void test();
};
Word.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/**
* Constructor. Initializes the value of the word and the URL where it was found.
*/
Word::Word(string v, URL u) : HTMLElement(v, HTMLElement::WORD), url(u) {
assert(v.length() > 0);
return;
}
string &Word::getURL(){
return url.getURL();
}
void Word::test(){
return;
}
I have a couple of questions:
1. Is there a way to get rid of my dummy function test() and still make the HTMLElement class abstract? [I guess I could implement the other methods in the derived classes, but that would give me code duplication]
2. Is there a way to access and modify the HTMLElement class variables (value, type) from within the derived classes? (Access/Change the value of HTMLElement.type from the Word class)
P.S. I'm a beginner, so please be as explicit as possible. I will really appreciate it!
1) If what you want is for it to be impossible to have a type that's just an HTMLElement (ie, you want ONLY derived types to be possible to instantiate), then you can just make the constructor protected intead of public. That way only derived classes will be able to access it.
Then you can get rid of that test() function.
2) They inherit those variables. You can just access them as if they were part of the derived class. Just say value = "whatever"; or something.