C++ :: Cast Directly Between Base Classes Of Object?
Jul 1, 2013
I've got two classes, which are both derived from the same two base classes. Here's a representation of the actual code:
Code: #include <vector>
class BaseClassA {
};
class BaseClassB {
};
class TestClassX
: public BaseClassA,
public BaseClassB
[code].....
Basically, I'd like to know if it is possible to cast directly from a BaseClassA pointer to a BaseClassB pointer, without casting to the child class first.
I programming currently something with OpenGL. Now I have written some wrapper classes, like Shader, Program .... All works fine, but I don't like to call Shader.GetHandle() every time I want to call a OpenGL function manually where I need the object handle/id. (GetHandle() returns the OpenGL ID of the object)
So now I wonder, is it possible to program it in C++ so, that I can put my objects to gl methods and c++ automatically pass the handle/id member to that function ? Is there maybe a operator that I can use for that?
I recall when I first started playing with C++ I was told that you should never use virtual functions unless you absolutely cannot think of a better way to do whatever you are attempting. This is something I have tried to stick to over the years - and indeed is probably why I have never used inheritance or polymorphism much in my own programmes.
However, I notice through a great deal of the code examples offered to questions here and even over on StackOverflow that commentators show no hesitation to recommend code that involves virtual functions. More so, I have even seen several instances here where - what I was taught as, but they may well have a different official name - 'pure virtual functions' (those with definitions inside a class of something like virtual int function_name(void)=0) are demonstrated and I was very clearly taught to avoid those like the plague.
I was wondering therefore has the official thinking changed since the middle nineties on when - and even whether - to use virtual functions in your programmes?
We want a solution in C++ that must be able to do the following:
Given a string of particular type, lets say 'A', we want to find all the types that derives from 'A'.
Instantiate new objects out of the types that are derived from 'A'.
E.g. Lets say we have a class, VehicleEntity. VehicleEntityhas child classes, PassangerCarEntity, TruckEntity, TrainEntity, BoatEntity.
We are unsure what vehicle entities there may be as the a library could be added containing more VehicleEntities. E.g. an AirplaneEntity thaterives from VehicleEntity could be added after deployment.
In the application, when a user wants to select a VehicleEntity, the user should be able to pick any of the entities deriving from VehicleEntity. This includes the PassangerCarEntity, TruckEntity, TrainEntity, BoatEntity and AirplaneEntity. The user selects an Entity, lets say AirplaneEntity, A new object of type AirplaneEntity must be instantiated.
The following is an concept example in C# of what we want to achieve in C++.
In C# the items for the dropdown list can be retrieved as follows:
Type vehicleEntityType = typeof(VehicleEntity); List<Type> types = new List<Type>(); foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
[Code] .....
We are aware that standard C++ does not contain any Metadata on its objects, and thus it is not possible without a workaround. It does not seem possible with RTTI and boost.Mirror.
So I have 2 seperate base classes, (note that I removed the variables and functions that do not relate to the topic) Object.h
class Object{ public: Object(); ~Object();
[Code].....
The error I get is saying I am calling a function declared with one calling convention with a function pointer declared with a different calling convention and this makes perfect sense because for some reason, the function pointer is pointed at the virtual function Object::update but I can't figure out why and how to make it point at the virtual function Drawable::getImage.
Also, the virtual update function is called in a different place just before this and works correctly.
Is there a way to copy a derived class object thru a pointer to base?
For example:
class Base { public: Base( int x ) : x( x ) {} private: int x; }; class Derived1 : public Base { public: Derived( int z, float f ) : Base( z ), f( f ) {} private: float f;}; class Derived2 : public Base { public: Derived( int z, string f ) : Base( z ), f( f ) {}
[Code] ....
The question is whether *B[0] would be a Derived1 object and *B[1] a Derived2 object?If not, how could I copy a derived class thru a pointer to the base class?
I create an instance of a base class (not derived class) and assign it to base class pointer. Then, I convert it to a pointer to a derived class and call methods on it.
why does it work, if there is a virtual table?
when will it fail?
// TestCastWin.cpp : Defines the entry point for the console application.//
I have a WordRecord that contains a LinkedList (both my doing). I have rigorously tested my LinkedList class, and know that it works (heck, I used it in the last project I had!). The problem is that undefined behaviour seems to happen when using the WordRecord, which has a std::string and a LinkedList<unsigned>. (The problem happens with the LinkedList.)
Here is the code:
main.cpp #include <iostream> #include "BinaryTreeNode.h" // here for test purposes #include "LexicographicTree.h" #include "LinkedList.h"//also for test purposes #include "OutputStream.h" #include "WordRecord.h" using namespace std; int main() { // setup the OutputStream to print to "test.txt" OutputStream stream("test.txt"); // create a sampleWordRecord (make it have the word "I" on line 1)
[code]....
One of the requirements for the project is that it must compile on Unix server (I am using Windows, and have tested it in both environments.) I get a core-dump in the Unix environment. On the other hand, the output on-screen in the Windows environment looks right. However, when I open up the text file, I get the following
Sample word record:
WordLines I{14} /* I have no what is happening to sampleWordRecord's LinkedList; I am not trying to modify it, except for where I created the sampleWordRecord! */
This refers to an ATL COM DLL project. I can successfully create a class hierarchy of objects, ie. say, one class is the TEAM, which then holds other objects, say, a leader and a secretary, both of which are Employee Classes . Here goes my question:
a) In the Team.h header file I declare m_pLeader as a CComPtr<IEmployee>
Code: classATL_NO_VTABLE CTeam : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CTeam, &CLSID_Team>, public IDispatchImpl<ITeam, &IID_ITeam, &LIBID_BUOBJ05Lib, /*wMajor =*/ 1, /*wMinor =*/ 0> { private: CComPtr<IEmployee> m_pLeader; CComPtr<IEmployee> m_pSecretary;
b) The Employee Class is defined within this ATL COM project. c) In the Team.cpp file, I create an instance in the FinalConstruct code, the focus is on the CEmployee
Code: HRESULT CTeam::FinalConstruct(){ CComObject<CEmployee>* pLeader; HRESULT hr=CComObject<CEmployee>::CreateInstance(&pLeader); if (FAILED(hr)) return hr; m_pLeader=pLeader; // ..same for secretary... return S_OK }
d) Here comes my QUESTION: How must I proceed if the Employee object was part of another ATL COM DLL, that is it would be described in another DLL that I would now like to reuse? I guess I need to
1. Have the other DLL's idl-, tlb, and h file in my project folder. Let me name it "other.h, other.idl, other.tlb"
2. Both h- and cpp-file must have an #include "other.h" statement -- please correct if I am wrong..
3. ...but how must in the Team's h- and cpp-files the statements be (assuming the class in the "other" Dll is Member (instead of Employee? I know the following code will NOT work, so I am asking how it should be correctly?
class Base { char * ptr; public: Base(){} Base(char * str)
[code].....
Obj1 is a derived class object where base class char pointer is initialized with "singh" and derived class char pointer is initilized with "sunil". I want to create Obj2 out of Obj1. Separate memory should be created for Obj2 char pointer (base part and derived part as well) and that should be initialized with the strings contained in Obj1.
Here the problem is: Derived class part can be initialized with copy constructor. How to initialize the base class char poniter of Obj2 with the base class part of Obj1. char pointers in both the classes are private.
I tried using initializer list but could not succeed.
I know if i will not use the pointer base class function "virtual double grossPay" will be called for both base class object and derived class object and when i will use pointer with reference to the object because base class function is virtual it will look for same function in derived class and if available it will execute it.
I am getting a compilation error from the code below. It is when i am naming a variable with my user defined type.
#include<iostream> #include<cstring> #include<cstdlib> using namespace std; class person {
[Code] .....
C:Dev-CppTRIAL.PASS.!!!.cpp In function `int main()': 66 C:Dev-CppTRIAL.PASS.!!!.cpp expected primary-expression before "p" 66 C:Dev-CppTRIAL.PASS.!!!.cpp expected `;' before "p" 74 C:Dev-CppTRIAL.PASS.!!!.cpp `p' undeclared (first use this function) (Each undeclared identifier is reported only once for each function it appears in.) 83 C:Dev-CppTRIAL.PASS.!!!.cpp `X' undeclared (first use this function)
"A nested class has free access to all the static members of the enclosing class. All the instance members can be accessed through an object of the enclosing class type, or a pointer or reference to an object."
How can the members be accessed through an object of the enclosing class type? I understand the pointer and reference part because for them you dont need the full definition, but for creating a object you do?
Also it has free access to all static members because the nested class is part of the enclosed class and with static it exists in everything inside the enclosing class? Right or am I missing something?
#include <iostream> #include "curve1.h" #include "curve2.h" using namespace std; int main() { Curve1 curve1Obj; Curve2 curve2Obj;
[Code]...
Base class Score has two derived classes Curve1 and Curve2. There are two curve() functions, one is in Curve1 and other in Curve2 classes. getSize() returns the value of iSize.
My base class header score.h looks like this:
#ifndef SCORE_H #define SCORE_H class Score { private: int *ipScore; float fAverage; int iSize;
[Code]...
You can see that I have used curve1Obj to enter scores, calculate average and output. So if I call getSize() function with cuve1Obj, it gives the right size that I took from user in enterScores() function. Also the result is same if I call getSize() in score.cpp definition file in any of the functions (obviously). .....
The problem is when I call curve() function of Curve2 class in main (line 23) with the object curve2Obj, it creates a new set of ipScore, fAverage and iSize (i think?) with garbage values. So when I call getSize() in curve() definition in curve2.cpp, it outputs the garbage. .....
How can I cause it to return the old values that are set in curve1.cpp?
Here is my curve2.cpp
#include <iostream> #include "curve2.h" using namespace std; void Curve2::curve() { cout << "getSize() returns: " << getSize() << endl; // out comes the garbage }
Can I use a function to simply put values from old to new variables? If yes then how?
I just wanted to add strings in any base form (example 1101+100 = 10001 in base-2 but it could be added using any base-form like in base-3 to base-36) and I'm having a big trouble with my code because it gave me incorrect results.
addition(char st[], char st2[], int base){ int i, j, carry = 0, ans, len, o=0, z=1, l=0; char final[50]; if(strlen(st)>=strlen(st2)) len = strlen(st); else len = strlen(st2);
I got this algorithm of conversion and now I'm stuck at how to code it.
"Algorithm to Convert From any Base to Base 10 Decimal."
Let 'n' be the number of digits in the number. For example, 104 has 3 digits, so 'n'=3. Let 'b' be the base of the number. For example, 104 is decimal so 'b' = 10. Let 's' be a running total, initially 0.
For each digit in the number, working left to right do:
Subtract 1 from 'n'. Multiply the digit times b^n and add it to 's'.
When done with all the digits in the number, the decimal value should be 's' .
I need to convert an integer, for example 10, to its base 16 equivalent, 16. I found this code that converts a base 16 number to base 10, but I need the opposite. Plus, this code doesn't seem to work properly with input values under 32.
Is there any way to read RAM memory directly. For say i want to access memory location 0x0100 to 0x120. How to do that. how to declare the variable, is it unsigned int. what is the type of read values it hex or ascii. how t cast it.
I'm successfully publishing an app to my website by publishing locally and then uploading the files but one of the options offered is to publish straight to the web site but I can't find anywhere to enter a user name and password for my web site. I could also do it with ftp but since the option is offered to publish directly to the web site I'd like to try that method. I'm using the Click Once method.
I wish to convert a character directly to a string for a top-secret project I'm working on. It needs to be portable across various machines with different sized Indians.
Code:
#include <stdio.h> int main(void) { const int i = 0x0041; const char *str_p = (char *) &i; }
[code]....
I want this to output an 'A', but I'm not sure this code will work on my friend's mom's S/360.
I don't know how to put this really, but I finished a program in Qt, and i want to know how to make a .exe file for it, so i dont have to open Qt and build the program every time i use it.
I have an array of (Student)classes created in Manager.h, which contains a new instance of class Name (name),(in Student.h)How would I go about accessing the SetFirstName method in Name.cpp if I was in a class Manager.cpp? I have tried using Students[i].name.SetFirstName("name");
// In Manager.h #include"Student.h" class Manager {
I'm learning OpenGL using the C API and some of the functions' argument types have proven a bit challenging to me.
One example is the function Code: glShaderSource(GLuint shader, GLsizei count, GLchar const** string, GLint const* length); It resides in foo() which receives a vector "data" from elsewhere Code: void foo(std::vector<std::pair<GLenum, GLchar const*>> const& data); To pass the pair's second element to glShaderSource's third argument, I do the following:
1. Can I initialize a char const** via initialization list, the way I do a char const*?
Code:
// this works std::vector<std::pair<GLenum, GLchar const*>> const shader_sources = { {GL_VERTEX_SHADER, "sourcecode"}, {GL_FRAGMENT_SHADER, "sourcecode"} }; // but is this possible?