Accessing Base class variable inside Derived class - c++11

I have a public inheritance, Derived struct inheriting from Base. The Base has a data member int i initialized to 5.
Now I have two codes.
Code 1 : Compiles fine
#include <iostream>
using namespace std;
struct Base{
int i = 5;
};
struct Derived: public Base{
int j = i; // Derived class able to use variable i from Base
Derived(){
i = 10; // Constructor of Derived able to access i from Base
}
};
int main()
{
Derived dobj;
cout << dobj.i;
return 0;
}
Code 2 : Gives error
#include <iostream>
using namespace std;
struct Base{
int i = 5;
};
struct Derived: public Base{
int j = i; //Still works
i = 10; // Error here " main.cpp:15:3: error: ā€˜iā€™ does not name a type"
Derived() = default;
};
int main()
{
Derived dobj;
cout<<dobj.i;
return 0;
}
Why is it that i can be used to assign and be assigned inside constructor body (as in code 1), but not used directly in Derived class (as in code 2). Also what does the error mean?
I was under the impression that the scope of Derived is nested inside Base, so shouldn't it be able to see the data members inside Base scope?

This has nothing to do with base and derived classes but with scope. Your code is illegal for the same reason that this code is illegal:
struct X
{
int i;
i = 20; // error
};
https://godbolt.org/z/60zPb-
int i; or int i = 10; are declarations. i = 20; is a statement. Statements can only appear in function bodies, not at class (or namespace) scope.

Related

Stateless Lambda and Private members

In certain cases when programming with libraries written in C involving callbacks, I like to use Lambda expressions; however, if I need to alter the state of a class member variable I can't juts pass this into a stateless(function pointer) lambda. But I can assign this to a data in a context structure. What I find strange is being able to access that member variable even if it's private in the class.
Here's an example code I wrote to demonstrate.
#include <iostream>
using std::cout;
typedef struct extradatatype{
void* data;
}extradata;
extradata e = {0};
typedef void(*callback)(extradata* e);
void cb(callback c){
c(&e);
}
class Test{
private:
int x;
public:
Test(int x){
this->x = x;
}
void setcb(){
cb([](extradata* e){
Test* self = reinterpret_cast<Test*>(e->data);
self->x = 20;
});
}
int getx(){
return x;
}
};
int main(){
Test t(10);
e.data = &t;
t.setcb();
cout << t.getx();
return 0;
}
In the Lambda expression Test* self is assigned to e->data but I can access self->x as if it were a public member instead of private. So what I'm confused about is, is the lambda expression expression being executed within the stack/context of the setcb function or is it being executed elsewhere as its own function but C++ is doing some weird trick to allow private members to be accessed. Because I assume a stateless lambda is really no different than a non member static function which has no access to private members of a class.
Since your lambda function is defined within the class Test context, it will have access to class Test private member (regardless if it's this.x or self.x where self is of type Test). It is similar to this example:
class Example {
private:
int x;
public:
int f(Example e) {
return e.x;
}
};
where, since f is a member of Example, it can access e.x because e has type Example.
If you move your lambda function definition out of the class context you'll see the expected error message:
void outside(extradata* e);
class Test{
private:
int x;
public:
void setcb(){
cb(outside);
}
};
void outside(extradata* e) {
Test* self = reinterpret_cast<Test*>(e->data);
self->x = 20; // error here!
}
test.cpp:32:11: error: 'int Test::x' is private within this context
self->x = 20;
^

Can a method of an class (in a shared_ptr) be tied to a static function in a traits class?

Historically, I've been using trait classes to hold information and apply that into a "generic" function that runs the same "algorithm." Only differed by the trait class. For example: https://onlinegdb.com/ryUo7WRmN
enum selector { SELECTOR1, SELECTOR2, SELECTOR3, };
// declaration
template < selector T> struct example_trait;
template<> struct example_trait<SELECTOR1> {
static constexpr size_t member_var = 3;
static size_t do_something() { return 0; }
};
template<> struct example_trait<SELECTOR2> {
static constexpr size_t member_var = 5;
static size_t do_something() { return 0; }
};
// pretend this is doing something useful but common
template < selector T, typename TT = example_trait<T> >
void function() {
std::cout << TT::member_var << std::endl;
std::cout << TT::do_something() << std::endl;
}
int main()
{
function<SELECTOR1>();
function<SELECTOR2>();
return 0;
}
I'm not sure how to create "generic" algorithms this when dealing with polymorphic classes.
For example: https://onlinegdb.com/S1hFLGC7V
Below I have created an inherited class hierarchy. In this example I have a base catch-all example that defaults all the parameters to something (0 in this case). And then each derived class sets overrides specific methods.
#include <iostream>
#include <memory>
#include <type_traits>
#include <assert.h>
using namespace std;
struct Base {
virtual int get_thing_one() {
return 0;
}
virtual int get_thing_two() {
return 0;
}
virtual int get_thing_three() {
return 0;
}
virtual int get_thing_four() {
return 0;
}
};
struct A : public Base {
virtual int get_thing_one() override {
return 1;
}
virtual int get_thing_three() override {
return 3;
}
};
struct B : public Base {
virtual int get_thing_one() override {
return 2;
}
virtual int get_thing_four() override{
return 4;
}
};
Here I created a simple factory, not elegant but for illustrative purposes
// example simple factory
std::shared_ptr<Base> get_class(const int input) {
switch(input)
{
case 0:
return std::shared_ptr<Base>(std::make_shared<A>());
break;
case 1:
return std::shared_ptr<Base>(std::make_shared<B>());
break;
default:
assert(false);
break;
}
}
So this is the class of interest. It is a class does "something" with the data from the classes above. The methods below are a simple addition example but imagine a more complicated algorithm that is very similar for every method.
// class that uses the shared_ptr
class setter {
private:
std::shared_ptr<Base> l_ptr;
public:
setter(const std::shared_ptr<Base>& input):l_ptr(input)
{}
int get_thing_a()
{
return l_ptr->get_thing_one() + l_ptr->get_thing_two();
}
int get_thing_b()
{
return l_ptr->get_thing_three() + l_ptr->get_thing_four();
}
};
int main()
{
constexpr int select = 0;
std::shared_ptr<Base> example = get_class(select);
setter l_setter(example);
std::cout << l_setter.get_thing_a() << std::endl;
std::cout << l_setter.get_thing_b() << std::endl;
return 0;
}
How can I make the "boilerplate" inside the setter class more generic? I can't use traits as I did in the example above because I can't tie static functions with an object. So is there a way to make the boilerplate example more common?
Somewhere along the lines of having a selector, say
enum thing_select { THINGA, THINGB, };
template < thing_select T >
struct thing_traits;
template <>
struct thing_traits<THINGA>
{
static int first_function() --> somehow tied to shared_ptr<Base> 'thing_one' method
static int second_function() --> somehow tied to shared_ptr<Base> 'thing_two' method
}
template <>
struct thing_traits<THINGB>
{
static int first_function() --> somehow tied to shared_ptr<Base> 'thing_three' method
static int second_function() --> somehow tied to shared_ptr<Base> 'thing_four' method
}
// generic function I'd like to create
template < thing_select T, typename TT = thing_traits<T> >
int perform_action(...)
{
return TT::first_function(..) + TT::second_function(..);
}
I ideally would like to modify the class above to something along the lines of
// Inside setter class further above
int get_thing_a()
{
return perform_action<THINGA>(...);
}
int get_thing_b()
{
return perform_action<THINGB>(...);
}
The answer is, maybe I can't, and I need to pass int the shared_ptr as a parameter and call the specific methods I need instead of trying to tie a shared_ptr method to a static function (in hindsight, that doesn't sound like a good idea...but I wanted to bounce my idea)
Whoever makes the actual call will need a reference of the object, one way or the other. Therefore, assuming you want perform_action to perform the actual call, you will have to pass the parameter.
Now, if you really want to store which function of Base to call as a static in thing_traits without passing a parameter, you can leverage pointer to member functions:
template <>
struct thing_traits<THINGA>
{
static constexpr int (Base::*first_function)() = &Base::get_thing_one;
...
}
template < thing_select T, typename TT = thing_traits<T>>
int perform_action(Base & b)
{
return (b.*TT::first_function)() + ...;
}
You can also play instead with returning a function object that does the call for you (and the inner function takes the parameter).
It all depends on who you need to make the call and what information/dependencies you assume you have available in each class/template.

Casting vtkSmartPointer to an Inherited Class

How do I cast a vtkSmartPointer<T> to an inherited class while maintaining reference counting?
Minimal illustration:
#include <iostream>
#include <vtkSmartPointer.h>
class A: public vtkObjectBase {
public :
A(){}
static A * New(){return new A();}
int var1 = 8;
};
class B: public A {
public :
B(){}
static B * New() {return new B();}
int var2 = 12;
};
int main (int argc, char ** argv) {
vtkSmartPointer<B> b = vtkSmartPointer<B>::New();
vtkSmartPointer<A> a = b; // this is fine
std::cout << "var1 = " << a->var1 << std::endl;
// this is not fine and I cannot find a vtk equivalent
// to boost's dynamic_pointer_cast for similar functionality
// vtkSmartPointer<B> c = a; // how do I do this?
}
I'm assuming there must be a macro somewhere similar to boost's dynamic_pointer_cast<T> but I can't find it. If there isn't, and someone can suggest a method to accomplish this, I would be very grateful.
There are a couple of problems here.
In most cases you want to inherit from vtkObject, not vtkObjectBase.
You are missing vtkTypeMacro().
What you are looking for is T::SafeDownCast().
So your code would become:
#include <vtkSmartPointer.h>
class A : public vtkObject {
public :
vtkTypeMacro(A, vtkObject);
A() = default;
static A* New() { return new A(); }
int var1 = 8;
};
class B : public A {
public:
vtkTypeMacro(B, A);
B() = default;
static B* New() { return new B(); }
int var2 = 12;
};
int main (int argc, char ** argv) {
vtkSmartPointer<B> b = vtkSmartPointer<B>::New();
vtkSmartPointer<A> a = b;
vtkSmartPointer<B> c = B::SafeDownCast(a);
}
For more information, please, consult VTK User Guide, chapter "14.6 Writing A VTK Class".
Okay nevermind, I found an answer that appears to work. I'll post it in case someone stumbles across here and wants to avoid the frustration I had.
It turns out that reference counting happens in the vtkObjectBase. So as long as code inherits from that, vtk will keep an accurate count. Thankfully vtk won't let you use vtkSmartPointer unless it does.
So it would seem that to implement a boost style macro one could simply do the following:
template<typename T,typename V> vtkSmartPointer<T> vtkDynamicPointerCast(vtkSmartPointer<V> src) {
T* v = dynamic_cast<T*>(src.Get());
if (v) return vtkSmartPointer<T>(v);
else return vtkSmartPointer<T>();
}

How to disable instantiating a temporary class?

I'm working with an expression template class which should not be instantiated to avoid dangling references. But I'm temped to declare a variable with auto and 'auto' create a named instance of a temporary class.
How can I disable auto declaration of temporary class in the following code?
class Base
{
};
class Temp : public Base
{
public:
Temp() {}
Temp(int, int) {}
Temp(const Temp&) = default;
Temp(Temp&&) = default;
};
Temp testFunc(int a, int b) {
return Temp{a,b};
}
int main() {
Base a = testFunc(1,2); // this should work
auto b = testFunc(1,2); // this should fail to compile
return 0;
}
You seem to want to prevent users from using auto on a particular type. That's not possible in any version of C++. If it is legal C++ for a user to write T t = <expr>;, where T is the type of <expr>, then it will be legal for a user to write auto t = <expr>; (ignoring class data members). Just as you cannot forbid someone from passing <expr> to a template function using template argument deduction.
Anything you do to prevent auto usage will also inhibit some other usage of the type.
One option would be to make Temp's constructors private, move testFunc inside the Temp class and make it static. This way you can still instantiate Base, but auto would fail because you would be calling a private constructor:
class Base
{
};
class Temp : public Base
{
Temp() {}
Temp(int, int) {}
Temp(const Temp&) = default;
Temp(Temp&&) = default;
public:
static Temp testFunc(int a, int b)
{
return Temp{a,b};
}
};
int main() {
Base a = Temp::testFunc(1,2); // this should work
auto b = Temp::testFunc(1,2); // this should fail to compile
return 0;
}
Demo

How to access virtual functions using vtable?

So I'm trying to access the virtual functions values using vtable. The way I understand it is that the compiler creates a pointer to the vtable, and a vtable is created for each class that contains a virtual function. I was able to get the values for the first two members. Now I don't understand how go about getting the values for 'bar' function.
#include <cstdio>
#include <iostream>
class Thing
{
private:
int x;
int y;
virtual int foo()
{
return x+y;
}
virtual int bar()
{
return x*y;
}
public:
Thing(){
x = 2;
y = 10;
}
};
int extract_x(void *thing)
{
// --- Begin your code ---
char* ptrA = (char*)thing;
ptrA=ptrA+8;
return *ptrA;
return 0;
// --- End your code ---
}
int call_bar(void* thing)
{
// --- Begin your code ---
// --- End your code ---
return 0;
}
int main()
{
Thing thing;
std::printf("%d %d\n",
extract_x(&thing),
call_bar(&thing));
return 0;
}
What you're trying to do is either unsupported/undefined, or if it is defined - quite imprudent. If A is a base class of B, and you believe your A* ptr is actually a B*, just use dynamic_cast<B*>(ptr) and access the B methods like a civilized human being... (but check the result the cast for being nullptr, in case it wasn't a B* after all.)

Resources