Type Casting

Hello, I have difficulties with type casting. Here I have 2 cases:

1)
1
2
3
4
5
const OntologyTreeNode** OntologyTreeNode::getChildren() const
{
const OntologyTreeNode** temp=(const OntologyTreeNode**)(this->children);
return temp;
}

2)
1
2
3
4
5
const string Investigator::getTaggedConcepts() const
{
const string* tmp = (const string*)(this->taggedConcepts);
return tmp;
}


The first one compiles, but the second says:
conversion from ‘const std::string*’ to non-scalar type ‘const std::string’ requested


What is the problem here. Thank you.
You probably shouldn't be typecasting. C-style casting is especially dangerous because the compiler doesn't check as closely as it should.

for #1, what is this->children and why do you need to cast it?

for #2, what is this->taggedConcepts and why do you need to cast it?


(when I say "what is it" I mean how is it defined / what is its variable type)
For the first one, I have a class with the following variables:
1
2
3
4
5
6
7
class OntologyTreeNode{
	private:
		string conceptName;
		OntologyTreeNode** children;
		int childCount;
		int height;
		int depth;


For the second one, another class with these variables:
1
2
3
4
5
6
class Investigator{
	private:
		string name;
		string* taggedConcepts;
		OntologyTree* ontologyTree;
		const void createOntology(const string& ontologyFilePath);



Yeah... there's no casting necessary:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const OntologyTreeNode** OntologyTreeNode::getChildren() const
{
//const OntologyTreeNode** temp=(const OntologyTreeNode**)(this->children);  // no need for this
//return temp;
  return children;
}

string Investigator::getTaggedConcepts() const  // no need to return a const object
{
//const string* tmp = (const string*)(this->taggedConcepts);
//return tmp;
  return *taggedConcepts;  // no need to cast, but you need to dereference the pointer
   // since you're returning an object, not a pointer
}
Worked for the second one, but first one now says:

invalid conversion from ‘OntologyTreeNode**’ to ‘const OntologyTreeNode**’



ah, right. That is a bad cast.

change the function to this:

1
2
3
4
const OntologyTreeNode* const * OntologyTreeNode::getChildren() const
{
  return children;
}


Note the extra const between the *'s

See this article for why that's necessary:

http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17
thank you,

what if for the second case I wanted to return members of taggedConcepts one by one? I don't know the size of this string array.
Topic archived. No new replies allowed.