Inheritance Question

I'm doing some Arduino programming and I was trying to add functions to an existing class by creating my own class and inheriting the existing one. However, I'm not sure how to go about using class members from the child class within the constructor for the parent class... or if this is even possible. Below is my pathetic attempt to convey my question in code.

If it helps, I'm trying to make a child class for the Keypad class that will include some extra functions without having to rewrite the parent constructor for the child class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class foo
{
public:
    foo();
    foo(int one, int two);
    ~foo();
};

class bar : public foo
{
public:
    bar();
    ~bar();
    
private:
    static const int dummy;
    static const int dummy1;
};

foo::foo(int one, int two)
{
    // do stuff with "one" and "two"
}

bar::bar()
{
    foo(dummy, dummy1);
}


Thanks in advance, and just tell me if I'm not making any sense at all.
If I understand you correctly, you'd do this with an initialization list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string>

class Book {
public :
	Book(const std::string _title) {title = _title;}

	std::string title;

};

class PetersBook : public Book {//not the greatest example, but whatever.
public :
	PetersBook(const std::string _title = "This is Peter's Book") : Book(_title) {}//default argument, and initialization list

};

int main(int argc, char* argv[]) {
	PetersBook pbook;

	std::cout << pbook.title << std::endl;

	pbook = PetersBook("This is still Peter's Book");

	std::cout << pbook.title << std::endl;

	std::cin.get();
	return 0;
}


Couldn't really think of a perfect, simple example.
Last edited on
That's exactly right. You can call a specific constructor of a parent class from within the child classes initializer list.

In your example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class foo
{
public:
    foo();
    foo(int one, int two);
    ~foo();
};

class bar : public foo
{
public:
    bar();
    ~bar();
    
private:
    static const int dummy;
    static const int dummy1;
};

foo::foo(int one, int two)
{
    // do stuff with "one" and "two"
}

bar::bar()
  : foo(dummy, dummy1)
{
}
Last edited on
Thank you both for the information!!
Topic archived. No new replies allowed.