w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Pass a pointer to a derived class pointer as a parameter to a constructor expecting a pointer to a base class pointer
Do either Derived* d = new Derived; Derived** d_ptr = &d; Manager* m = new Manager(*d_ptr); or Derived* d = new Derived; Derived** d_ptr = &d; // not needed ? Manager* m = new Manager(d);

Categories : C++

Returning a different class pointer by overloaded operator new in a class
In general , operator new() should not CREATE an object, it should create space for an object. Your code will overwrite a B object with an A object, and then use it as a B object, and yes, that would be "undefined" (probably covered in the docs under "casting an object to a different type that it wasn't originally created as). This may appear to work in this particular case, but if the constructor of B is more complex (e.g. there are virtual functions in B), it would immediately fail to work correctly. If you want to allocate memory for an object, you could do:L void* A::operator new(size_t sz) { void* ptr = (void*)::new unsigned char[sz]; return ptr; } Now you are not calling two different constructors for the same object!

Categories : C++

Returning class pointer C++
According to the error message: message_window* get_message_window(string title,string msj,int s){ should be: message_window* windows::get_message_window(string title,string msj,int s){

Categories : C++

C++: Returning a class variable
Your constructor is assigning to its arguments instead of the object's private fields. Use an initialization list, or explicitly qualify the assignment targets with this, or pick different argument names: Coordinate::Coordinate(int x, int y) : x(x), y(y) { cout << x << endl; } or Coordinate::Coordinate(int x, int y) { this->x = x; this->y = y; cout << x << endl; } or Coordinate::Coordinate(int xVal, int yVal) { x = xVal; y = yVal; cout << x << endl; }

Categories : C++

Passing a pointer to a variable or the address of a pointer to a variable result in the same behavior
myfunc(&pointer_to_device) results in undefined behaviour. Presumably it appears to work for you because you don't access any members of MyObj when calling or inside hello. To demonstrate this, try the same program with an updated version of MyObj class MyObj { const char* str; public: MyObj() : str("hello") {} void hello() { printf("%s ", str); } };

Categories : C++

Specializing class for generic function returning pointer to function
I believe this will work if you specialize it as: template<typename FpResultType, typename FpArg1, typename Arg1, typename Arg2> A<ResultType (*(Arg1, Arg2))(FpArg1)> {...}; I tested with the following code, which compiles successfully (using Clang): template<typename T> class A; template<typename FnRetT, typename FnArgT, typename Arg1, typename Arg2> class A<FnRetT (*(Arg1, Arg2))(FnArgT)> { public: typedef FnRetT fn_ret_t; }; float foo(float a) { return a; } float (*getfn(int arg1, int arg2))(float) { return foo; } int main(int argc, const char * argv[]) { typedef A<decltype(getfn)>::fn_ret_t ret_ty; return 0; } Note that the syntax used to match the function type matches the declaration of getfn.

Categories : C++

Pointer to a variable and pointer to an array of one element
You can use "sizeof()" operator which is helpful in determining pointer to an array or pointer to a variable. When we pass an array name to "sizeof()", it gives the total size of array in bytes while when we pass a plain pointer it gives the address length.

Categories : C++

Casting a pointer to a method of a derived class to a pointer to a method of a base class
No. This is described in section 4.11 of the standard (I have n3337.pdf draft): A prvalue of type “pointer to member of B of type cv T”, where B is a class type, can be converted to a prvalue of type “pointer to member of D of type cv T”, where D is a derived class (Clause 10) of B. If B is an inaccessible (Clause 11), ambiguous (10.2), or virtual (10.1) base class of D, or a base class of a virtual base class of D, a program that necessitates this conversion is ill-formed. The result of the conversion refers to the same member as the pointer to member before the conversion took place, but it refers to the base class member as if it were a member of the derived class. The result refers to the member in D’s instance of B. Since the result has type “pointer

Categories : C++

What's the difference between a pointer, and a pointer variable?
p is a pointer variable, that points to a variable i. We can simply call it pointer. A declaration: int* p; int i; p = &i; declares p as the identifier of an int type object. This is usually stated more succinctly as 'p is a pointer to i'. p can be use to refer int variable i after expression p = &i. To access value of variable i using pointer p you can use Dereference operator * (e.g. *p). Anf i = 10; equivalent to *p = 10;. Also notice in expression p = &i; to read address of i I used & ampersand operator also called Address of operand. Pointer is just a logical address (a identifier by which a variable can be referenced). The C standard does not define what a pointer is internally and how it works internally. You would like to read: What exactly is a C poi

Categories : C

Where is a pointer variable's address stored when referencing a character variable?
Does the variable example simply have it's own address? Yes, the variable has its own address. Do the strings I have within the array each have a memory address different to *example and each other? Yes, each string has its own address, different from each other's. It's also different from the address of the variable example. The expression *example, however, is not the same as the variable example. See the next. Does the pointer example just simply reference each address and also initialize what's in each address as shown by the declaration of the strings? The variable example references the array of strings in the sense that the value of example (not its address) is the address of the array.

Categories : C

Pointer crashing while returning - C
The things they POINT TO are the same value, but they are not at the same location (or you wouldn't need to check for their values being the same). Also, be careful about using *; *source_pt_cpy isn't a pointer, its what that pointer points to, and if that's what you were returning, then using that value as a pointer could very likely cause a seg fault.

Categories : C

Error when returning a pointer
That code compiles and runs just fine in gcc in both c90 and c99 mode, so there's a couple of things you can do. First and foremost, you should show us the actual error (that should have come with the original question). Second, get a hex dump of the file to make sure there's no funny characters in it, such as with the command od -xcb myprog.c. Thirdly, it's also good practice to return values from functions where you specify a non-void return type. Later iterations of C make this unnecessary for main but earlier iterations could result in random values being passed back to the environment. I still return zero from main even though I no longer have to (it's hard to break a thirty-year habit). That last point may be what's happening here, depending on which compiler and version you're u

Categories : C

How does returning pointer from a function work?
In main when you delete p you are actually deleting the root pointer in the t object! Don't do that, or you will have undefined behavior, which is what you experience here. When you return a pointer, you return a copy of the pointer, both pointers will point to the same object. If you then delete one of the pointers, the other pointer will now point to a deleted object.

Categories : C++

Function returning a pointer to an int array
int(*)[10] is a pointer to an array of 10 ints. int* is a pointer to int. These are different types. However, an array decays to a pointer to its first element, so you can do: int a[10]; int(*p)[10] = &a; int* q = a; // decay of int[10] to int* But not: q = p; p = q;

Categories : C++

Declaring a private, thread specific, variable in a kernel and then returning that variable to the host
Yes it is possible. Declaring a local variable in a kernel is private to each thread that you launch. So simply declare a variable, use it, and when you want to store result in the host , copy it to global memory. You could give a location to global memory passing a pointer to it as argument to the kernel. Example: __global__ void kernel(float *var) { float localVar;//local to each thread in execution ... //Computation which uses localVar ... *var = localVar; } After you use cudaMemcpy() to get it in the host. This example also is valid if you declare a local array. In that case you just have to copy an array instead of a single variable. Edit#1: Example of passing an array as argument to a kernel: __global__ void kernel(float *arrayPtr, int length) { .... } arrayPtr is a de

Categories : Multithreading

C++ Safe returning a pointer to an iterater after map insert?
Well I'd say that depends on is your map alive longer than anything that could use (and store) the pointer. If yes, (ie, it's in some sort of singleton), you could go with it, but not very safe anyway since any code could delete the pointer. The best option is to store boost::shared_ptr (or std:: since c++11) instead of raw pointers in your mapn and return only a weak_ptr after insertion. That way, you're sure no other code can delete your pointer as long as the map holds it, and that no one can use a pointer that has been erased from the map.

Categories : C++

When returning a collection pointer, how does the client know if it needs to destroy it?
If you want the caller to know they take responsibility for the pointer, then use this: std::unique_ptr<QList<Foo *>> methodBar(int someParam); Another advantage is that the caller would have to go out of their way to make the memory not be automatically freed. A std::unique_ptr cannot be copied, only moved, so passing a std::unique_ptr fairly explicitly causes the responsibility of freeing the memory to be moved from the callee to to the caller. Note that this would also imply that the objects that are pointed to inside the list are not the responsibility of the caller. If you wanted those objects also to be the responsibility of the caller, you would use: std::unique_ptr<QList<std::unique_ptr<Foo>>> methodBar(int someParam);

Categories : C++

Chaining commands by returning this pointer/reference in C# without assignment
In C#, if I return this, the value is copied This is not true, at least for classes. Classes in C# are reference types, that means every variable of that type is actually a reference, so returning this just returns a reference to the current instance. So to do this, it's essentially the same in C#: public class Foo { public Foo Transform(Bar bar) { // transform return this; } public Foo TransformDifferently(Yay yay) { // transform return this; } } For value types, it should return a new instance of the type. Value types are supposed to be immutable, so if you've designed your struct correctly, there should be no method which modifies the original. Transform should modify a new version of the struct instead.

Categories : C#

What did compiler do in this piece of code(Base class pointer to derived class object)?
There is UB here, since you are trying to delete array of type B, that has dynamic type D. n3376 5.3.4/3: In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined Also, since you want to work polymorphycally - you should make d-tor of base class virtual.

Categories : C++

ObjectiveC passing class Pointer to static library and then calling methods from class
Declare a protocol like this in your static library: @protocol AppDelegateRequiredMethods @required ... methods here ... @end Then, import the header that declares that protocol into your various AppDelegate implementations and declare your app delegate as implementing said protocol: @interface MyAppDelegate:NSObject <AppDelegateRequiredMethods> ... @end

Categories : Iphone

assigning a base class pointer to a derived class object created in the free store
When you delete an object of a derived type through a pointer to the base type, the base type must have a virtual destructor. Without it you have undefined behavior. So: add a virtual destructor to Base1 and to Base2.

Categories : C++

Null pointer exception when refactoring the creation of an ArrayList of PGraphics from the main class into a separate class
In your constructor for PGraphicsMaker, you declare a local variable parent and assign pa to it. PApplet parent = pa; ... when I'm sure you intended to assign it to the instance variable parent: parent = pa; In your code, the instance variable parent stays null until it's accessed, and a NullPointerException results.

Categories : Java

How can I pass pointer-pointers of a derived class as a based class?
I've reconstructed your example using dynamic_cast and I had no problems constructing TradeHelper this way. Is there a reason you can't use dynamic_cast in your code? Trader trader; Bond b; trader._bond = &b; Trader* t = &trader; Instrument* inst = dynamic_cast<Instrument*>(t->_bond); if (inst == NULL) { std::cout << "dynamic_cast failed!" << std::endl; return 1; } TradeHelper* th = new TradeHelper(&inst); delete th;

Categories : C++

Why can't a static nested class access "this" pointer of outer class?
The difference between a static nested class and one that isn't static is precisely that an instance of a non-static inner class is associated with a specific instance of the enclosing class, while a static inner class isn't. There is no A.this for an instance of a static inner class to be associated with.

Categories : Java

Derived class specific functions, inside an overridden virtual function, being called by a base class pointer
If you call pBaseClass->AFunc() and pBaseClass is actually a B then B::AFunc() is what gets called. If pBaseClass is actually an A then A::AFunc() is what gets called. That's the whole point of polymorphism. What B::AFunc() does is up to B, there's no reason it can't call other functions or use data within B that don't exist in A.

Categories : C++

How to access pointer of a class pointing to another pointer of a class pointing to a value
In the simplified pseudocode that you have posted, you are accessing the myvalue attribute correctly and since it is zero-initialized in the A's constructor and being incremented afterwards, there is no reason why its value should become negative. This seems to be rather caused by some bug (hidden within your real code) that rewrites myvalue's value. But what catches my attention more is that you have: class C { public: C() { bPtr = new B(); } B* bPtr; Now if the lifetime of instance of B contained within instance of C is tied to the lifetime of that instance of C, it seems to be reasonable for the bPtr to be aggregated by value ~> i.e. to be an object with automatic storage duration rather than a pointer: class C { public: C() { } B b; which will reduce the ugly memory management c

Categories : C++

C++ Running a function pointer of class A from within class B as callback
sayHello should be a static function. Because ordinary member functions have implicit parameter ¨this¨. So the full signature of sayHello is void sayHello(Foo* this); Another way - use pointer to class member. Also you can use functor structure instead of function.

Categories : C++

c++ convert a pointer to a class into a instance of a class
Assuming you want p contents destroyed, write a move constructor for MyClass. In general, storing raw pointers like you do is problematic in general. If you used vector<double> instead, the whole task would be much easier, because in this approach unnecessary use of pointers is only adding you problems. That's how I'd do that: class MyClass{ std::vector<double> a; public: MyClass(unsigned int N): a(N) { } // no destructor! }; class MyOtherClass{ MyClass p; public: MyOtherClass(unsigned int N) : p(N) {}; // no destructor!! MyClass& getMyClass() { return p; }; } Now it can be clearly seen you can't just use getMyClass to initialize new MyClass without copying, because it's a reference. However, if you are sure you won't need to use MyOtherCl

Categories : C++

Must a pointer to an instance of class A be static in class B?
Hard to tell without the full relevant code, but I would guess MainWindow is being deallocated. I would further guess MainWindow is originaly stored in the stack, rather than the heap, because what causes the address to change is a function call (which alters the stack). My advice: verify if either MainWindow or MdiChildWindowA and MdiChildWindowB (not sure which pMainWindow changes) are local variables and if so, change your code, so that they get allocated in the heap, i.e. dynamicaly through the use of the keyword new. Answering the second question, pointers are not treated differently from any other type, in essence they are very much like integers, but their content is promptly allowed to be interpreted as memory addresses.

Categories : C++

initialize member variable of base class inside child class and use in other class
There are two instances of BaseClass in the example you posted. One is the one instantiated with new ChildClass() and the other one is instantiated by the main() method (TestClass). Each one of them, being a subclass of BaseClass, has its own test member (they are different variables with different values). Remember that the this keyword always references the instance in which it is used. In this case, System.out.println(this.test); is accessing the test property of the TestClass instance created in the main method. You need to access the test property of the other instance. You could do so by keeping a reference to the ChildClass instance and accessing the test property afterwards: ChildClass instance = new ChildClass().initialize(); System.out.println(instance.test); You

Categories : Java

Incompatible pointer types returning 'UITableViewCell *__strong' from a function with result type 'UITableView *' when try to view records
The return type of your function is wrong. It should return UITableViewCell* and not UITableView* -(UITableViewCell*)tableview:(UITableView *)tableview cellForRowAtIndexPath: (NSIndexPath *)indexPath; Hope that helps!

Categories : IOS

Get static variable from class stored in Class variable
Yes, but only via the reflection API. Field f = cls.getField("staticVariable"); int variable = f.getInt(null); There will be a lot of exceptions for you to catch here.

Categories : Java

C++: Global variable as pointer
You are right in your hypothesis of where the objects are located. About usage, It's horses for courses. There is no definite rule, it depends on the design & the type of functionality you want to implement. For example: One may choose the pointer version to achieve lazy initialization or polymorphic behavior, neither of which is possible with global non pointer object approach.

Categories : C++

How to point to a pointer variable
You can use & on a pointer just like on any other variable. In your case, it looks like you might want to change del to: Node *del(Node **N, int v) And then call it like: x = del(&someNode, 12);

Categories : C

when a base class pointer point to a base class object whether the compiler will use dynamic binding?
It can choose whichever, or neither, depending on how smart it is and how well it can detect. The rule is polymorphism must work. How this is achieved is an implementation detail. If the same end-result can be achieved with both dynamic or static binding, as is the case here, both are valid options for the compiler. In your case, the function doesn't have to be called at all - the generated code could be just as well identical to code generated by int main() { cout << "base class"; }

Categories : C++

Class template where variable class derives from certain abstract class
Use std::is_base_of: template <class A> class B { static_assert(std::is_base_of<C, A>::value , "A must derive from C"); //... }; Note that is_base_of<C, C>::value is true, so you may want to also use std::is_same to ensure A is not actually C itself: static_assert(std::is_base_of<C, A>::value && !std::is_same<C, A>::value , "A must derive from C");

Categories : C++

Is a variable defined with "char *" a pointer or a variable of type char in c?
By writing char *myvariable, int foo, double blah, or void (*funcptr)(void), you are declaring a variable with some type. The type of the variable specifies what is stored in that variable: a pointer, number, or structure. So, char *myvariable is a variable (some reserved amount of memory) that contains a pointer value.

Categories : C

When assigning pointer to pointer I get warning: assignment makes integer from pointer
uint8_t* buffer, curr, next; The way you wrote it, buffer is a pointer and curr and next are mere uint8_ts. You probably meant: uint8_t *buffer, *curr, *next; Even better (less prone to errors) would be to have each field on its own line.

Categories : C

Declare stack variable without specifying the name and get the pointer
There's no way to do this by allocating on the stack. However, you can use std::make_shared for the heap: #include <memory> std::shared_ptr<Var> p = std::make_shared<Var>();

Categories : C++

const variable value is changed by using a pointer
It is possible to change it but the behavior is undefined, as its mentioned in the standard! Its in c11 under 6.7.3 If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined. If an attempt is made to refer to an object defined with a volatile-qualified type through use of an lvalue with non-volatile-qualified type, the behavior is undefined.

Categories : C



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.