I've been away from C++ for a while, and I'm having a little trouble with this one. I'll spare you my bad code - can someone please post a 'model answer' for how to write a simple header file and source file for a small class with a constructor that accepts a few values, and passes a few on to it's base classes constructor? I'm worried that I'm making something inline by mistake. Thank you.
Sometimes the simplest answers are the hardest to find clear examples of on the internet.
// ExampleClass.h
#ifndef ExampleClass_H_
#define ExampleClass_H_
#include "ExampleBase.h"
class ExampleClass : public ExampleBase {
public:
ExampleClass(int a);
};
#endif
// ExampleClass.cpp
#include "ExampleClass.h"
ExampleClass::ExampleClass(int a) : ExampleBase(a)
{
// other constructor stuff here
}
The initializer list is used to initialize the base classes. Initialize base classes before instance members. Non-virtual base classes are initialized from left to right, so if you have multiple bases, initialize them in the order they are declared.
Here's an example of passing arguments to the base class constructor:
#include <iostream>
struct Base {
Base(int i) {
std::cout << i << std::endl;
}
};
struct Derived : public Base {
Derived(int i) : Base(i) {}
};
Seeing as the OP requested non-inline versions, I'll repost with modifications.
struct Base {
Base (int);
};
struct Derived : public Base {
Derived (int);
};
Derived :: Derived (int i)
: Base (i)
{
}
class Parent
{
// Parent Constructor
Parent(int x)
{
// Constructor Code
}
};
class Child : public Parent
{
// Child Constructor
Child(int x, int y, int z) : Parent(x)
{
// Constructor Code
}
};
Related
Why does this code:
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
};
int main(void)
{
B *b = new B(5);
delete b;
}
Result in these errors:
main.cpp: In function ‘int main()’:
main.cpp:13: error: no matching function for call to ‘B::B(int)’
main.cpp:8: note: candidates are: B::B()
main.cpp:8: note: B::B(const B&)
Shouldn't B inherit A's constructor?
(this is using gcc)
If your compiler supports C++11 standard, there is a constructor inheritance using using (pun intended). For more see Wikipedia C++11 article. You write:
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
using A::A;
};
This is all or nothing - you cannot inherit only some constructors, if you write this, you inherit all of them. To inherit only selected ones you need to write the individual constructors manually and call the base constructor as needed from them.
Historically constructors could not be inherited in the C++03 standard. You needed to inherit them manually one by one by calling base implementation on your own.
For templated base classes, refer to this example:
using std::vector;
template<class T>
class my_vector : public vector<T> {
public:
using vector<T>::vector; ///Takes all vector's constructors
/* */
};
Constructors are not inherited. They are called implicitly or explicitly by the child constructor.
The compiler creates a default constructor (one with no arguments) and a default copy constructor (one with an argument which is a reference to the same type). But if you want a constructor that will accept an int, you have to define it explicitly.
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
public:
explicit B(int x) : A(x) { }
};
UPDATE: In C++11, constructors can be inherited. See Suma's answer for details.
This is straight from Bjarne Stroustrup's page:
If you so choose, you can still shoot yourself in the foot by inheriting constructors in a derived class in which you define new member variables needing initialization:
struct B1 {
B1(int) { }
};
struct D1 : B1 {
using B1::B1; // implicitly declares D1(int)
int x;
};
void test()
{
D1 d(6); // Oops: d.x is not initialized
D1 e; // error: D1 has no default constructor
}
note that using another great C++11 feature (member initialization):
int x = 77;
instead of
int x;
would solve the issue
You have to explicitly define the constructor in B and explicitly call the constructor for the parent.
B(int x) : A(x) { }
or
B() : A(5) { }
How about using a template function to bind all constructors?
template <class... T> Derived(T... t) : Base(t...) {}
Correct Code is
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
public:
B(int a):A(a){
}
};
main()
{
B *b = new B(5);
delete b;
}
Error is b/c Class B has not parameter constructor and second it should have base class initializer to call the constructor of Base Class parameter constructor
Here is how I make the derived classes "inherit" all the parent's constructors. I find this is the most straightforward way, since it simply passes all the arguments to the constructor of the parent class.
class Derived : public Parent {
public:
template <typename... Args>
Derived(Args&&... args) : Parent(std::forward<Args>(args)...)
{
}
};
Or if you would like to have a nice macro:
#define PARENT_CONSTRUCTOR(DERIVED, PARENT) \
template<typename... Args> \
DERIVED(Args&&... args) : PARENT(std::forward<Args>(args)...)
class Derived : public Parent
{
public:
PARENT_CONSTRUCTOR(Derived, Parent)
{
}
};
derived class inherits all the members(fields and methods) of the base class, but derived class cannot inherit the constructor of the base class because the constructors are not the members of the class. Instead of inheriting the constructors by the derived class, it only allowed to invoke the constructor of the base class
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
B(int x):A(x);
};
int main(void)
{
B *b = new B(5);
delete b;
}
I'm trying to practice some polymorphism and i got into some issues.
Here's my code :
class A{ //the base
public:
A(){}
virtual void Log(){};
virtual ~A(){};
private:
protected:
int __value;
};
class B : public A{ //the derived
public:
B(int value):__value(value){} //here's the problem
void Log() override{
std::cout<<__value<<"\n";
}
~B(){};
};
At that lines the error said : "class 'B' does not have any field named '__value'". It does work if i will do it in this way :
class A{
public:
A(){}
virtual void Log(){};
virtual ~A(){};
private:
protected:
int __value;
};
class B : public A{
public:
B(int value){
__value=value;
}
void Log() override{
std::cout<<__value<<"\n";
}
~B(){};
};
I know what i've tried works while i'm accesing the private members, but I want to know if there is some way to make the first attempt work too.
Thanks!
C++ does not work this way. Only a class's constructor can initialize its members.
Only A's constructor can initialize its class member. That's what a constructor's job is. A derived class cannot initialize its base class's members, only it's own class members. A base class only initializes the base class's members. A derived class's constructor can initialize only its own class's members.
What you need to do is add a constructor to A, perhaps a protected constructor, with a parameter that initializes the class member with the parameter:
class A {
// ...
A(int value) : __value{value} {}
// ...
};
And have the derived class's constructor explicitly invoke this constructor.
B(int value) : A{value}
{
}
In some situations you can also delegate the constructor, as an alternative. This should be covered in the advanced C++ chapters of your C++ book.
P.S. You should use modern C++'s uniform initialization syntax, with {...} instead of (...). If you're using an older C++ book that doesn't cover uniform initialization syntax, you should get a more recent book.
I know it's OK to call base class function in a derived class constructor, because base class is constructed before derived class.But I'm not sure if this is a good practice.Example code is:
class Base {
public:
int Get() const { return i_; }
void Set(const int i) { i_ = i; }
private:
int i_{0};
};
class Derived : public Base {
// initialize `derived_i_` with a call to base class function, Is this a good
// practice in production code?
Derived() : derived_i_{Get()} {
// do some other things
}
private:
int derived_i_{0};
};
To be more pedantic, you could write your constructor as the following:
Derived() : Base(), derived_i_{Get()} {
// do some other things
}
The compiler should fully construct the base class before doing any initialization of the derived class.
Is there a way to set a private member variable of a base class to a value in the constructor of a derived class?
I understand that's what getter and setter methods are for and what making the variable protected or public is for, but assuming you can't modify the base class, is there any alternate way to set it?
No. It's private. That is the whole point of private.
From the clarifications in the comments - the base class does give you a way to do it via its constructor, so you can use that.
// Assuming MyBaseclass has a 1 int constructor to set the
// private member, then something like this works.
//
MySubclass(int x) : MyBaseclass(x) {}
I understand that's what getter and setter methods are for and what making the variable protected or public is for, but assuming you can't modify the base class, is there any alternate way to set it?
Sure. The alternative way instead of using setter functions in the derived class constructor body, is to use an appropriate constructor from your derived class to call an initializing constructor of the base class (as you state it exists in your comment):
class Base {
public:
Base(int x, int y) : x_(x), y_(y) {}
private:
int x_;
int y_;
};
class Derived : public Base {
public:
Derived() : Base(15,42) {}
// ^^^^^^^^^^^^^
}:
See more details about the member initializer list.
Yes, we can do so by calling a getter function from the base class. Here is an example:
#include<iostream>
using namespace std;
class A{
int x;
public:
void setx(int x1) {
x = x1;
}
int getx() {
return x;
}
};
class B: public A {
};
int main() {
B b;
b.setx(1000);
cout << b.getx();
return 0;
}
I learnt the work of virtual functions: if the inherited classes inherit a function from the base class, and it is custom for each ones, I can call these functions with pointers that point to the base class, this way:
BaseClass* PointerName = &InheritedClassObject;
But what about variables? I found this question on the site that tells: I can't create virtual variables in C++. My experience proves it: for variables, Visual C++ says: 'virtual' is not allowed.
Then, what is the way to reach the value of a(n inherited) variable that belongs to an inherited class by using base class pointers?
Based off your comment, I think what you are trying to ask if how do child classes access their parent's variables. Consider this example:
class Parent
{
public:
Parent(): x(0) {}
virtual ~Parent() {}
protected:
int x;
};
class Child: public Parent
{
public:
Child(): Parent(), num(0) {}
private:
int num;
};
void Child::foo()
{
num = x; //Gets Parent's x,
}
NB: If you define an x in Child, that masks the x in Parent. So, if you want to get the x in Parent, you would need: Parent::x. To simply get x from a Child c, you use c.x if x is public or use a getter if x is protected or private:
int Child::getNum()
{
return num;
}
You don't. Virtual functions use them, do whatever needs to be done and return result if needed.
You can't use any function, data member of an inherited class if it's casted back to base class. However, you can alter those variables with virtual functions. Example:
#include <iostream>
class BaseClass {
public:
BaseClass() {}
virtual void do_smth() = 0;
private:
};
class InheritedClass: public BaseClass {
public:
InheritedClass(): a(1) {}
virtual void do_smth() { std::cout << ++a << std::endl; }
private:
int a;
};
int main() {
BaseClass* ptr = new InheritedClass();
ptr->do_smth();
return 0;
}
In this piece of code, virtual function did alteration of variable belongs to InheritedClass.