C/C++ :: When To Use Class And When To Use Pointer To A Class
Apr 29, 2015
I want to ask about pointers to classes vs just classes. I have used classes such as QTimer with and without pointers, and I don't know when to use pointers. Sometimes you can't because a function returns a class, not a pointer to a class. But usually you can do either.
When should you use a pointer?
View 4 Replies
ADVERTISEMENT
Feb 6, 2015
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.//
#include "stdafx.h"
#include <iostream>
class B
{
public:
B(double x, double y) : x_(x), y_(y) {}
double x() const { return x_; }
[Code] ....
View 14 Replies
View Related
Mar 21, 2015
In this book, item 3 is about never treat arrays polymorphically. In the latter part of this item, the author talks about the result of deleting an array of derived class objects through a base class pointer is undefined. What does it mean? I have an example here,
Code:
class B
{
public:
B():_y(1){}
virtual ~B() {
cout<<"~B()"<<endl;
[Code] ....
This sample code does exactly what I want. So does the author mean the way I did is undefined?
View 1 Replies
View Related
Nov 29, 2013
My program is a basic MFC AppWizard (exe) created project in VC++ 6. In MainFrm.cpp, I am trying to access some user defined CMyView member functions. However when I try to do the standard procedure to get the CMyView pointer in MainFrm.cpp, I get the " ... 'CMyView' : undeclared identifier" error. To resolve this, I add " #include myView.h " at the top of MainFrm.h which then produces the following errors:
Code:
myview.h(21) : error C2143: syntax error : missing ';' before '*'
myview.h(21) : error C2501: 'CMyDoc' : missing storage-class or type specifiers
myview.h(21) : error C2501: 'GetDocument' : missing storage-class or type specifiers
What do these errors mean? Is there a simple way to access CMyView member functions from CMainFrame?
View 8 Replies
View Related
Jun 28, 2012
I'm trying to implement a class hierarchy and a wrapper class with a pointer to the base class. The base class has operator< overloaded and the implementation makes use of virtual functions as some of the logic for sorting is in the derived classes. Unfortunately, when trying to use the base class operator< from the wrapper, I get a "pure virtual method called".
Below code is meant to illustrate my problem. Unfortunately it crashes on me (upon destruction of vec) and I cannot quite see, why. So two questions:
1. spot the error I made in the code below (having lived in Java-land for the last 5 years, I'm sure I just did some stupid error)?
2. How can I implement Wrapper::operator< to use Base::operator<? I know I could write a function and pass it to sort but I'm interessted if there is a way to actually use Base::operator<.
Code:
#include <vector>
#include <algorithm>
#include <cmath>
[Code].....
View 3 Replies
View Related
Oct 3, 2012
I have encountered a problem I can't see to solve. I want to access a function and can't seem to find the right combination to get me there. Here is what I am looking at:
CFoo1::CFoo2::GetStrDataC(int nRow) const
How do I call the GetStrDataC function from another class?
View 6 Replies
View Related
Aug 19, 2014
I am attempting to implement function pointers and I am having a bit of a problem.
See the code example below; what I want to be able to do is call a function pointer from another pointer.
I'll admit that I may not be explaining this 100% correct but I am trying to implement the code inside the main function below.
class MainObject;
class SecondaryObject;
class SecondaryObject {
public:
[Code]....
View 10 Replies
View Related
Aug 2, 2013
I'm currently reading the C++ Guide for Dummies
Anyway right now I'm working with pointers and classes, and when I create a new pointer for my class it looks like this...
Pen *Pointerpen = new Pen;
But in the book they threw in this...
Pen *Pointerpen = new Pen();
Can you actually designate memory space for a function? Or was this a typo on their part? It's never come up before and they didn't explain it.
View 5 Replies
View Related
May 18, 2013
A pointer to base class, if assigned to a derived class, only points to the base part right? So you can only use the base part of the derived class with that pointer and no methods from the derived class?
View 8 Replies
View Related
Feb 4, 2014
I came across a piece of c++ code that seems to be initializing a class object like this:
ImapMailbox *mailbox;
Now the class looks like this:
class ImapMailbox {
public:
ImapMailbox();
ImapMailbox (const QString& mailbox);
~ImapMailbox();
// Methods
void addMessage (ImapMessage *message);
[Code]...
And the constructor looks like this:
ImapMailbox::ImapMailbox()
: d(new ImapMailboxPrivate)
{
d->unseen = d->exists = d->recent = 0;
d->readWrite = false;
d->flags = 0;
}
But this does not seem to be an array like object. So what exactly could this be pointing to?
View 2 Replies
View Related
Aug 29, 2014
I have a query regarding virtual destructor functionality. So below is sample code:
Code:
#include<iostream>
#include<stdlib.h>
using namespace std;
class Base
Code: Base *b = d;
Here b and d now pointing to same memory location.
Now below statement:
Code: delete (b);
Here since my destructor is virtual it will call derived class and base class destructor.
Now my question is, if I use this:
Code: delete (d); // And without virtual keyword in ~Base() {} This call both derived and base class destructor.
So which one is correct form to call and why? Is delete(b) is standard in virtual function mechanism.
Output is:
D1 :: function1()
Base :: function2()
INSIDE D1 DES
INSIDE BASE DES
View 2 Replies
View Related
Jan 10, 2015
I have the following scenario :
Code:
class test {
public :
int num;
};
int main() {
test t1;
test *ptr = &t1;
int test :: *mem_ptr = &test::num;
}
I need to access mem_ptr (pointer to a class member) through :
a. object (t1)
b. pointer to the object (ptr).
How can i do that ?
View 4 Replies
View Related
Oct 10, 2013
If I need a static pointer to a class that is used globally(multiple files), and I only want to allocate memory once.
One way is to create a function that returns a static pointer of type class and call it where ever you need this pointer. My question is there another way to do this like with a header file and include the header file where you need to use the object of type class.
static class* function
{
static class c;
if (c == NULL)
{
c = new class;
}
return c
}
View 1 Replies
View Related
Aug 4, 2013
#include <iostream>
#include <vector>
#include <string>
#include <map>
using namespace std;
struct bop {
string realname; //real name
[Code] ....
Okay, so first thing's first. The program will not compile due to lines 39-45. If I were to change those pointers into regular objects, it will not change the values of my class object. So what is the right way to do this?
I want the user to be able to input the # of employers/programmers into the system. But I cannot do that with an array of classes because when declaring an array; the array size must be constant.
View 6 Replies
View Related
Feb 3, 2015
If i have a pointer array of classes, e.g. MyClass *foo; and if i try to delete this pointer delete [] foo; does it call a destructor of a class, or wahat happens? this is because i have another pointers in that class which are cleared in destructor.
View 1 Replies
View Related
Nov 11, 2014
smart pointer class is the one that take in charge of release allocated resource when itself destroyed.
recently,i want design a smart pointer class, it take in charge of release resource allocated by new or new[].
my problem how to design destructor, you should determine the pointer ptr is pointer an array or a single object.
the structure of this smart point class may be:
template<class T>;
class smart_pointer{
public:
smart_pointer(T* p):ptr(p){};
~smart_pointer(){
[Code] ......
View 6 Replies
View Related
Mar 20, 2013
Lets say we have a class that holds a pointer member to another object. If I delete that pointer in the destructor I get an error (and I understand why). My question is : is it possible to overcome that without memory leaks ?
1 #include<iostream>
2 using namespace std;
3
4 class A {
5 public:
6 ~A() {
7 cout<< "~A()" <<endl;
[Code] ....
View 5 Replies
View Related
Aug 19, 2014
I have the following problem: I am using NLOpt for optimization. The API provides functions to set the objective. This is done as follows:
double objective(const vector<double> &x, vector<double> &grad, void *data)
{
return x[1]*x[0];
}
int main(){
nlopt::opt opti(nlopt::LD_MMA,2);
opti.set_min_objective(objective,NULL);
vector<double> x(2);
[Code]....
Now I want to make the function objective a member of a class:
class Foo {
public:
double objective(...){..}
};
How can I give this method to opti.optimize? If I make objective static I can use
opti.optimize(Foo::objective,NULL);
but I do not want to have a static member. Is it possible to create an object of type Foo and give it to opti.optimize?
View 1 Replies
View Related
Nov 11, 2014
I am stucked in a problem of overloading arithmetic operators such as "+,*" for a class in the form
class Point {
int N; // dimension of the point
double *Pos; // length of N
}
My assign operator is :
Point& Point::operator= (const Point& pt) {
N= pt.N;
if(Pos == NULL) Pos = new double[N];
memcpy(Pos, pt.Pos, N*sizeof(double));
[Code] ....
The add operator "+" is:
Point operator+( const Point& pt1, const Point& pt2 ) {
Point ptr = Point(pt); // this is a constructor
for (int i=0; i<pt1.N; i++) ptr.Pos[i] += pt2.Pos[i];
return ptr;
}
Based on the above overloading, What I am going to do is :
P = alpha*P1 + beta*P2; // alpha and beta are double constants, P1 and P2 are Points objes
It is ok with Intel C++ 14.0 compiler, but does not work with the microsoft visual c++ 2012 compiler in debug mode in visual studio 2012.
I stepped in those operators and found that visual c++ compiler deconstructs the ptr in operators "*" and "+" before its return while intel c++ finished the operation P = alpha*P1 + beta*P2; and delete those ptrs at last.
Portability of my operator overloading is worse. How to get those arithmetic operators overloading for class with pointers in it.
View 3 Replies
View Related
Nov 30, 2013
I have a class Calendar which has an attribute of priority queue, that accepts records of structure defined as:
typedef void (Calendar::*eventPointer)();
struct activationRecord {
double Time;
int Priority;
eventPointer activationEvent;
};
And here is the problem. Whole day I've been trying to fill the Calendar with some test entries by calling the method
void Calendar::calendarPush(double Time, int Priority, eventPointer event)
This is how I call it
calendar.calendarPush(Time, Priority, &Calendar::calendarEmpty);
But Visual Studio keeps to warn me with this error
argument of type "bool (Calendar::*)()" is incompatible with parameter of type "eventPointer *"
#include <iostream>
#include "Calendar.h"
using namespace std;
int main() {
cout << "Initializing ..." << endl;
double Time = 0.0;
int Priority = 0;
[Code] ....
View 4 Replies
View Related
Feb 14, 2013
lets say I have a pointer p_unit of type c_unit* (c_unit is an a.b.c.)
I have a function that returns a pointer to a new c_unit object:
c_unit * man_add_unit() {
c_unit * local_p_unit;
unsigned short int local_run_code;
print_man_add_menu();
local_run_code = get_a_run_code(); // this bit just gets user input
switch (local_run_code)
[code]....
I assign that to p_unit, then add it to a vector v_units:
p_unit = man_add_unit();
v_units.push_back(p_unit);
cout << "New unit added.
";
The whole program runs on a loop, and another thing the user can do is to print out data on c_unit objects pointed to by v_units. The problem is, in that function up there ^ I give the user the option to go back to main menu without creating a unit.
Since "local_p_unit" is declared but not assigned an initial value, I'm guessing the function would return a "null" pointer (which is what's hanging me up). If I just let this run with the above code, and go to print out the unit data, the program crashes.
I tried to make an if thing with p_unit == 0 but this always returns false and doesn't catch the "bad" unit that will subsequently cause a crash.
Btw, I have considered assigning a reference to a generic c_unit object to that there local_p_unit so it won't return null, then remove pointers to that object from v_units at the end of the loop.. But I know there's got to be a better way.
View 4 Replies
View Related
Jan 30, 2013
Here is the assignment: (3pts) Given the following class header file, write the class’ source code for each of the accessor and mutator functions listed. (How the functions have listed their parameters, varying between passing by reference and by value.) Don’t forget to comment your code – it counts!
class Album {
private:
char * artist; // band or singer’s name
char * title; // title of the album
[code]....
The input will be an array. My questions: First, am I on the right track?
When using (char * a) for a function, for example, this is passing the address of a, correct? so then *artist=a; changes what the address of a points to?
also, the functions are bool when I would expect void. Why? for all of the set_" " functions, the parameter is *... but for set_record_label it is *&. That appears to be a mistake to me. Is that right?
what is the difference between *& and * as parameters?
View 5 Replies
View Related
Jun 16, 2013
#include<fstream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
class Student {
private: int ID,Hour; char Name[20],Sex[7]; float Rate,Salary,Amount;
[Code] ......
View 1 Replies
View Related
Mar 30, 2014
I am having trouble with the array pointer and with the variables. I don't seem to have the pointer set up because the additional times the array is called it is empty. Also, if I don't use integers the program drops through. where I am going wrong?
Question is in the code
/*
NumClass
Main.cpp
*******************************************************************************************
*
* Design a class that has an array of floating point numbers. The constructor should accept an integer argument and dynamically allocate the array to hold that many numbers. The destructor should free the memory held by the array. In addition, there should be member functions to perform the following operations:
*
**Store a number in any element in of the array
[code].....
View 1 Replies
View Related
Nov 6, 2013
Right now I have code
#include <iostream>
using namespace std;
class Rectangle {
private:
double width;
double length;
[Code] .....
it gives error ...
View 1 Replies
View Related
Oct 14, 2013
I have a function called,
App 1:
void GetImage(CImage * img) {
//Pass &img over socket to another app
}
App 2:
void DisplayImage() {
CImage * pImg = &img;
}
Is it possible to pass a class pointer as memory buffer across the socket? The above code is just an example. My question in general is, whether it's possible to pass any Classes pointer as a memory buffer across sockets.
View 7 Replies
View Related