Question 1.2 Forward declaration • Write the following forward class declaration
ID: 3914706 • Letter: Q
Question
Question 1.2 Forward declaration
• Write the following forward class declarations for Parent and Child.
class Child; // forward statement that class "Child" exists
class Parent; // forward statement that class "Parent" exists
class Parent {
public:
Parent();
string getName() const;
void setName(string n);
void addChild(const Child &c);
int numChildren() const;
const vector& getChildren() const;
private:
string name;
vector children;
};
class Child {
public:
Child(string n, int a, const Parent &pt);
string getName() const;
int getAge() const;
const Parent* getParent() const;
private:
string name;
int age;
Parent p;
};
• The Parent and Child class mention each other, but do not do anything.
• The function bodies have not been written yet.
• In the Parent class, the reference to the vector for getChildren() is const because we do not want an external application to change somebody’s children.
• In the Child class, the pointer for getParent() is const because we do not want an external application to change somebody’s parent.
Explanation / Answer
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Child; // forward statement that class "Child" exists
// forward statement that class "Parent" exists
class Parent {
public:
Parent(){
name = "";
}
string getName() const {
return name;
}
void setName(string n){
name = n;
}
void addChild(const Child &c){
children.push_back(c);
}
int numChildren() const{
return children.size();
}
const vector<Child>& getChildren() const{
return children;
}
private:
string name;
vector <Child>children;
};
class Child {
public:
Child(string n, int a, const Parent &pt){
name = n;
age = a;
p.setName(pt.getName());
vector<Child> b = pt.getChildren();
vector<Child> c = p.getChildren();
for (int i = 0; i< b.size(); i++){
c.push_back(b[i]);
}
}
string getName() const{
return name;
}
int getAge() const{
return age;
}
const Parent* getParent() const{
return &p;
}
private:
string name;
int age;
Parent p;
};
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.