Search Results

Search found 3956 results on 159 pages for 'constructor overloading'.

Page 3/159 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Member function overloading/template specialization issue

    - by Ferruccio
    I've been trying to call the overloaded table::scan_index(std::string, ...) member function without success. For the sake of clarity, I have stripped out all non-relevant code. I have a class called table which has an overloaded/templated member function named scan_index() in order to handle strings as a special case. class table : boost::noncopyable { public: template <typename T> void scan_index(T val, std::function<bool (uint recno, T val)> callback) { // code } void scan_index(std::string val, std::function<bool (uint recno, std::string val)> callback) { // code } }; Then there is a hitlist class which has a number of templated member functions which call table::scan_index(T, ...) class hitlist { public: template <typename T> void eq(uint fieldno, T value) { table* index_table = db.get_index_table(fieldno); // code index_table->scan_index<T>(value, [&](uint recno, T n)->bool { // code }); } }; And, finally, the code which kicks it all off: hitlist hl; // code hl.eq<std::string>(*fieldno, p1.to_string()); The problem is that instead of calling table::scan_index(std::string, ...), it calls the templated version. I have tried using both overloading (as shown above) and a specialized function template (below), but nothing seems to work. After staring at this code for a few hours, I feel like I'm missing something obvious. Any ideas? template <> void scan_index<std::string>(std::string val, std::function<bool (uint recno, std::string val)> callback) { // code }

    Read the article

  • Recursion problem overloading an operator

    - by Tronfi
    I have this: typedef string domanin_name; And then, I try to overload the operator< in this way: bool operator<(const domain_name & left, const domain_name & right){ int pos_label_left = left.find_last_of('.'); int pos_label_right = right.find_last_of('.'); string label_left = left.substr(pos_label_left); string label_right = right.substr(pos_label_right); int last_pos_label_left=0, last_pos_label_right=0; while(pos_label_left!=string::npos && pos_label_right!=string::npos){ if(label_left<label_right) return true; else if(label_left>label_right) return false; else{ last_pos_label_left = pos_label_left; last_pos_label_right = pos_label_right; pos_label_left = left.find_last_of('.', last_pos_label_left); pos_label_right = right.find_last_of('.', last_pos_label_left); label_left = left.substr(pos_label_left, last_pos_label_left); label_right = right.substr(pos_label_right, last_pos_label_right); } } } I know it's a strange way to overload the operator <, but I have to do it this way. It should do what I want. That's not the point. The problem is that it enter in an infinite loop right in this line: if(label_left<label_right) return true; It seems like it's trying to use this overloading function itself to do the comparision, but label_left is a string, not a domain name! Any suggestion?

    Read the article

  • Empty constructor or no constructor

    - by Ram
    Hi, I think it is not mandatory to have a default constructor in a class (C#). So in that situation shall I have a empty constructor in the class or I can skip it? Is it a best practice to have a default empty constructor? Class test { test() { } ...... } or Class test { ...... }

    Read the article

  • testing if constructor in constructor chain

    - by Delan Azabani
    I'm attempting to implement a GTK+ inspired widget toolkit for the web in JavaScript. One of the constructor chains goes gtk.widget => gtk.container => gtk.bin => gtk.window Every gtk.widget has a showAll method, which, if and only if the widget is a gtk.container or derivative (such as gtk.bin or gtk.window), will recursively show the children of that widget. Obviously, if it isn't a gtk.container or derivative, we shouldn't do anything because the widget in question can't contain anything. For reference, here is my inheritance function; it's probably not the best, but it's a start: function inherit(target, parent) { target.prototype = new parent; target.prototype.constructor = target; } I know that I can check for the direct constructor like this: if (this.constructor === gtk.container) ... However, this only tests for direct construction and not, say, if the object is a gtk.bin or gtk.window. How can I test whether gtk.container is somewhere up in the constructor chain?

    Read the article

  • Const operator overloading problems in C++

    - by steigers
    Hello everybody, I'm having trouble with overloading operator() with a const version: #include <iostream> #include <vector> using namespace std; class Matrix { public: Matrix(int m, int n) { vector<double> tmp(m, 0.0); data.resize(n, tmp); } ~Matrix() { } const double & operator()(int ii, int jj) const { cout << " - const-version was called - "; return data[ii][jj]; } double & operator()(int ii, int jj) { cout << " - NONconst-version was called - "; if (ii!=1) { throw "Error: you may only alter the first row of the matrix."; } return data[ii][jj]; } protected: vector< vector<double> > data; }; int main() { try { Matrix A(10,10); A(1,1) = 8.8; cout << "A(1,1)=" << A(1,1) << endl; cout << "A(2,2)=" << A(2,2) << endl; double tmp = A(3,3); } catch (const char* c) { cout << c << endl; } } This gives me the following output: NONconst-version was called - - NONconst-version was called - A(1,1)=8.8 NONconst-version was called - Error: you may only alter the first row of the matrix. How can I achieve that C++ call the const-version of operator()? I am using GCC 4.4.0. Thanks for your help! Sebastian

    Read the article

  • Init var without copy constructor

    - by Ockonal
    Hello, I have some class(Window) without copy constructor (it's private). I can't understand how to init var of this class in my own class: class MyClass { Window obj; // Hasn't copy constructor public: void init() { obj = Window(/* constructor params */); // [error] obj(/* constructor params */); // [error] } } Error 1: initializing argument 1 of ‘Window::Window(WindowHandle, const sf::WindowSettings&)’ Error 2: ‘NonCopyable& NonCopyable::operator=(const NonCopyable&)’ is private But it works in this way: Window obj(/* constructor params */);

    Read the article

  • Doubt about constructor in JAVA

    - by Harry Joy
    I have few doubts regarding constructor in java Can a constructor be private? If yes then in which condition? Constructor is a method or not? If constructor does not return anything then why we are getting a new Object every time we call it. Whats the default access modifier of a constructor if we did not specify. Thanks & Regards Edit---------- Answer for 1 & 3 are very clear. But still doubt about 2&4 as i'm getting different answers for them.

    Read the article

  • new and delete operator overloading

    - by Angus
    I am writing a simple program to understand the new and delete operator overloading. How is the size parameter passed into the new operator? For reference, here is my code: #include<iostream> #include<stdlib.h> #include<malloc.h> using namespace std; class loc{ private: int longitude,latitude; public: loc(){ longitude = latitude = 0; } loc(int lg,int lt){ longitude -= lg; latitude -= lt; } void show(){ cout << "longitude" << endl; cout << "latitude" << endl; } void* operator new(size_t size); void operator delete(void* p); void* operator new[](size_t size); void operator delete[](void* p); }; void* loc :: operator new(size_t size){ void* p; cout << "In overloaded new" << endl; p = malloc(size); cout << "size :" << size << endl; if(!p){ bad_alloc ba; throw ba; } return p; } void loc :: operator delete(void* p){ cout << "In delete operator" << endl; free(p); } void* loc :: operator new[](size_t size){ void* p; cout << "In overloaded new[]" << endl; p = malloc(size); cout << "size :" << size << endl; if(!p){ bad_alloc ba; throw ba; } return p; } void loc :: operator delete[](void* p){ cout << "In delete operator - array" << endl; free(p); } int main(){ loc *p1,*p2; int i; cout << "sizeof(loc)" << sizeof(loc) << endl; try{ p1 = new loc(10,20); } catch (bad_alloc ba){ cout << "Allocation error for p1" << endl; return 1; } try{ p2 = new loc[10]; } catch(bad_alloc ba){ cout << "Allocation error for p2" << endl; return 1; } p1->show(); for(i = 0;i < 10;i++){ p2[i].show(); } delete p1; delete[] p2; return 0; }

    Read the article

  • Binary operator overloading on a templated class (C++)

    - by GRB
    Hi all, I was recently trying to gauge my operator overloading/template abilities and as a small test, created the Container class below. While this code compiles fine and works correctly under MSVC 2008 (displays 11), both MinGW/GCC and Comeau choke on the operator+ overload. As I trust them more than MSVC, I'm trying to figure out what I'm doing wrong. Here is the code: #include <iostream> using namespace std; template <typename T> class Container { friend Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs); public: void setobj(T ob); T getobj(); private: T obj; }; template <typename T> void Container<T>::setobj(T ob) { obj = ob; } template <typename T> T Container<T>::getobj() { return obj; } template <typename T> Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs) { Container<T> temp; temp.obj = lhs.obj + rhs.obj; return temp; } int main() { Container<int> a, b; a.setobj(5); b.setobj(6); Container<int> c = a + b; cout << c.getobj() << endl; return 0; } This is the error Comeau gives: Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2 Copyright 1988-2008 Comeau Computing. All rights reserved. MODE:strict errors C++ C++0x_extensions "ComeauTest.c", line 27: error: an explicit template argument list is not allowed on this declaration Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs) ^ 1 error detected in the compilation of "ComeauTest.c". I'm having a hard time trying to get Comeau/MingGW to play ball, so that's where I turn to you guys. It's been a long time since my brain has melted this much under the weight of C++ syntax, so I feel a little embarrassed ;). Thanks in advance. EDIT: Eliminated an (irrelevant) lvalue error listed in initial Comeau dump.

    Read the article

  • Polynomial division overloading operator (solved)

    - by Vlad
    Ok. here's the operations i successfully code so far thank's to your help: Adittion: polinom operator+(const polinom& P) const { polinom Result; constIter i = poly.begin(), j = P.poly.begin(); while (i != poly.end() && j != P.poly.end()) { //logic while both iterators are valid if (i->pow > j->pow) { //if the current term's degree of the first polynomial is bigger Result.insert(i->coef, i->pow); i++; } else if (j->pow > i->pow) { // if the other polynomial's term degree is bigger Result.insert(j->coef, j->pow); j++; } else { // if both are equal Result.insert(i->coef + j->coef, i->pow); i++; j++; } } //handle the remaining items in each list //note: at least one will be equal to end(), but that loop will simply be skipped while (i != poly.end()) { Result.insert(i->coef, i->pow); ++i; } while (j != P.poly.end()) { Result.insert(j->coef, j->pow); ++j; } return Result; } Subtraction: polinom operator-(const polinom& P) const //fixed prototype re. const-correctness { polinom Result; constIter i = poly.begin(), j = P.poly.begin(); while (i != poly.end() && j != P.poly.end()) { //logic while both iterators are valid if (i->pow > j->pow) { //if the current term's degree of the first polynomial is bigger Result.insert(-(i->coef), i->pow); i++; } else if (j->pow > i->pow) { // if the other polynomial's term degree is bigger Result.insert(-(j->coef), j->pow); j++; } else { // if both are equal Result.insert(i->coef - j->coef, i->pow); i++; j++; } } //handle the remaining items in each list //note: at least one will be equal to end(), but that loop will simply be skipped while (i != poly.end()) { Result.insert(i->coef, i->pow); ++i; } while (j != P.poly.end()) { Result.insert(j->coef, j->pow); ++j; } return Result; } Multiplication: polinom operator*(const polinom& P) const { polinom Result; constIter i, j, lastItem = Result.poly.end(); Iter it1, it2, first, last; int nr_matches; for (i = poly.begin() ; i != poly.end(); i++) { for (j = P.poly.begin(); j != P.poly.end(); j++) Result.insert(i->coef * j->coef, i->pow + j->pow); } Result.poly.sort(SortDescending()); lastItem--; while (true) { nr_matches = 0; for (it1 = Result.poly.begin(); it1 != lastItem; it1++) { first = it1; last = it1; first++; for (it2 = first; it2 != Result.poly.end(); it2++) { if (it2->pow == it1->pow) { it1->coef += it2->coef; nr_matches++; } } nr_matches++; do { last++; nr_matches--; } while (nr_matches != 0); Result.poly.erase(first, last); } if (nr_matches == 0) break; } return Result; } Division(Edited): polinom operator/(const polinom& P) const { polinom Result, temp2; polinom temp = *this; Iter i = temp.poly.begin(); constIter j = P.poly.begin(); int resultSize = 0; if (temp.poly.size() < 2) { if (i->pow >= j->pow) { Result.insert(i->coef / j->coef, i->pow - j->pow); temp = temp - Result * P; } else { Result.insert(0, 0); } } else { while (true) { if (i->pow >= j->pow) { Result.insert(i->coef / j->coef, i->pow - j->pow); if (Result.poly.size() < 2) temp2 = Result; else { temp2 = Result; resultSize = Result.poly.size(); for (int k = 1 ; k != resultSize; k++) temp2.poly.pop_front(); } temp = temp - temp2 * P; } else break; } } return Result; } }; The first three are working correctly but division doesn't as it seems the program is in a infinite loop. Final Update After listening to Dave, I finally made it by overloading both / and & to return the quotient and the remainder so thanks a lot everyone for your help and especially you Dave for your great idea! P.S. If anyone wants for me to post these 2 overloaded operator please ask it by commenting on my post (and maybe give a vote up for everyone involved).

    Read the article

  • Polynomial division overloading operator

    - by Vlad
    Ok. here's the operations i successfully code so far thank's to your help: Adittion: polinom operator+(const polinom& P) const { polinom Result; constIter i = poly.begin(), j = P.poly.begin(); while (i != poly.end() && j != P.poly.end()) { //logic while both iterators are valid if (i->pow > j->pow) { //if the current term's degree of the first polynomial is bigger Result.insert(i->coef, i->pow); i++; } else if (j->pow > i->pow) { // if the other polynomial's term degree is bigger Result.insert(j->coef, j->pow); j++; } else { // if both are equal Result.insert(i->coef + j->coef, i->pow); i++; j++; } } //handle the remaining items in each list //note: at least one will be equal to end(), but that loop will simply be skipped while (i != poly.end()) { Result.insert(i->coef, i->pow); ++i; } while (j != P.poly.end()) { Result.insert(j->coef, j->pow); ++j; } return Result; } Subtraction: polinom operator-(const polinom& P) const //fixed prototype re. const-correctness { polinom Result; constIter i = poly.begin(), j = P.poly.begin(); while (i != poly.end() && j != P.poly.end()) { //logic while both iterators are valid if (i->pow > j->pow) { //if the current term's degree of the first polynomial is bigger Result.insert(-(i->coef), i->pow); i++; } else if (j->pow > i->pow) { // if the other polynomial's term degree is bigger Result.insert(-(j->coef), j->pow); j++; } else { // if both are equal Result.insert(i->coef - j->coef, i->pow); i++; j++; } } //handle the remaining items in each list //note: at least one will be equal to end(), but that loop will simply be skipped while (i != poly.end()) { Result.insert(i->coef, i->pow); ++i; } while (j != P.poly.end()) { Result.insert(j->coef, j->pow); ++j; } return Result; } Multiplication: polinom operator*(const polinom& P) const { polinom Result; constIter i, j, lastItem = Result.poly.end(); Iter it1, it2, first, last; int nr_matches; for (i = poly.begin() ; i != poly.end(); i++) { for (j = P.poly.begin(); j != P.poly.end(); j++) Result.insert(i->coef * j->coef, i->pow + j->pow); } Result.poly.sort(SortDescending()); lastItem--; while (true) { nr_matches = 0; for (it1 = Result.poly.begin(); it1 != lastItem; it1++) { first = it1; last = it1; first++; for (it2 = first; it2 != Result.poly.end(); it2++) { if (it2->pow == it1->pow) { it1->coef += it2->coef; nr_matches++; } } nr_matches++; do { last++; nr_matches--; } while (nr_matches != 0); Result.poly.erase(first, last); } if (nr_matches == 0) break; } return Result; } Division(Edited): polinom operator/(const polinom& P) { polinom Result, temp; Iter i = poly.begin(); constIter j = P.poly.begin(); if (poly.size() < 2) { if (i->pow >= j->pow) { Result.insert(i->coef, i->pow - j->pow); *this = *this - Result; } } else { while (true) { if (i->pow >= j->pow) { Result.insert(i->coef, i->pow - j->pow); temp = Result * P; *this = *this - temp; } else break; } } return Result; } The first three are working correctly but division doesn't as it seems the program is in a infinite loop. Update Because no one seems to understand how i thought the algorithm, i'll explain: If the dividend contains only one term, we simply insert the quotient in Result, then we multiply it with the divisor ans subtract it from the first polynomial which stores the remainder. If the polynomial we do this until the second polynomial( P in this case) becomes bigger. I think this algorithm is called long division, isn't it? So based on these, can anyone help me with overloading the / operator correctly for my class? Thanks!

    Read the article

  • C++ Operator overloading - 'recreating the Vector'

    - by Wallter
    I am currently in a collage second level programing course... We are working on operator overloading... to do this we are to rebuild the vector class... I was building the class and found that most of it is based on the [] operator. When I was trying to implement the + operator I run into a weird error that my professor has not seen before (apparently since the class switched IDE's from MinGW to VS express...) (I am using Visual Studio Express 2008 C++ edition...) Vector.h #include <string> #include <iostream> using namespace std; #ifndef _VECTOR_H #define _VECTOR_H const int DEFAULT_VECTOR_SIZE = 5; class Vector { private: int * data; int size; int comp; public: inline Vector (int Comp = 5,int Size = 0) : comp(Comp), size(Size) { if (comp > 0) { data = new int [comp]; } else { data = new int [DEFAULT_VECTOR_SIZE]; comp = DEFAULT_VECTOR_SIZE; } } int size_ () const { return size; } int comp_ () const { return comp; } bool push_back (int); bool push_front (int); void expand (); void expand (int); void clear (); const string at (int); int operator[ ](int); Vector& operator+ (Vector&); Vector& operator- (const Vector&); bool operator== (const Vector&); bool operator!= (const Vector&); ~Vector() { delete [] data; } }; ostream& operator<< (ostream&, const Vector&); #endif Vector.cpp #include <iostream> #include <string> #include "Vector.h" using namespace std; const string Vector::at(int i) { this[i]; } void Vector::expand() { expand(size); } void Vector::expand(int n ) { int * newdata = new int [comp * 2]; if (*data != NULL) { for (int i = 0; i <= (comp); i++) { newdata[i] = data[i]; } newdata -= comp; comp += n; delete [] data; *data = *newdata; } else if ( *data == NULL || comp == 0) { data = new int [DEFAULT_VECTOR_SIZE]; comp = DEFAULT_VECTOR_SIZE; size = 0; } } bool Vector::push_back(int n) { if (comp = 0) { expand(); } for (int k = 0; k != 2; k++) { if ( size != comp ){ data[size] = n; size++; return true; } else { expand(); } } return false; } void Vector::clear() { delete [] data; comp = 0; size = 0; } int Vector::operator[] (int place) { return (data[place]); } Vector& Vector::operator+ (Vector& n) { int temp_int = 0; if (size > n.size_() || size == n.size_()) { temp_int = size; } else if (size < n.size_()) { temp_int = n.size_(); } Vector newone(temp_int); int temp_2_int = 0; for ( int j = 0; j <= temp_int && j <= n.size_() && j <= size; j++) { temp_2_int = n[j] + data[j]; newone[j] = temp_2_int; } //////////////////////////////////////////////////////////// return newone; //////////////////////////////////////////////////////////// } ostream& operator<< (ostream& out, const Vector& n) { for (int i = 0; i <= n.size_(); i++) { //////////////////////////////////////////////////////////// out << n[i] << " "; //////////////////////////////////////////////////////////// } return out; } Errors: out << n[i] << " "; error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const Vector' (or there is no acceptable conversion) return newone; error C2106: '=' : left operand must be l-value As stated above, I am a student going into Computer Science as my selected major I would appreciate tips, pointers, and better ways to do stuff :D

    Read the article

  • Operator overloading outside class

    - by bobobobo
    There are two ways to overload operators for a C++ class: Inside class class Vector2 { public: float x, y ; Vector2 operator+( const Vector2 & other ) { Vector2 ans ; ans.x = x + other.x ; ans.y = y + other.y ; return ans ; } } ; Outside class class Vector2 { public: float x, y ; } ; Vector2 operator+( const Vector2& v1, const Vector2& v2 ) { Vector2 ans ; ans.x = v1.x + v2.x ; ans.y = v1.y + v2.y ; return ans ; } (Apparently in C# you can only use the "outside class" method.) In C++, which way is more correct? Which is preferable?

    Read the article

  • Operator overloading C++ outside class

    - by bobobobo
    Well, so there are 2 ways to overload operators for a C++ class INSIDE CLASS class Vector2 { public: float x, y ; Vector2 operator+( const Vector2 & other ) { Vector2 ans ; ans.x = x + other.x ; ans.y = y + other.y ; return ans ; } } ; OUTSIDE CLASS class Vector2 { public: float x, y ; } ; Vector2 operator+( const Vector2& v1, const Vector2& v2 ) { Vector2 ans ; ans.x = v1.x + v2.x ; ans.y = v1.y + v2.y ; return ans ; } In C# apparently you can only use the OUTSIDE class method The question is, in C++, which is "morer-correcter?" Which is preferable? When is one way better than another?

    Read the article

  • C# Operator Overloading post-fix increment

    - by Victor
    I'm coding a date class and am having trouble with the post-fix increment (the prefix increment seems fine). Here is the sample code: public class date { int year, month, day; public date(int d, int m, int y) { day = d; month = m; year = y; } static public date operator ++(date d) { return d.Next(d); } } The method "Next(date d)" takes a date and returns tomorrows date (I left it out for brevity). I'm to young in C# to understand why the prefix is fine but postfix increment does nothing. But remember in C++ we would have to have two methods instead of just one - for prefix and postfix increments. Also no errors or warnings on compile.

    Read the article

  • overloading friend operator<< for template class

    - by starcorn
    Hello, I have read couple of the question regarding my problem on stackoverflow now, and none of it seems to solve my problem. Or I maybe have done it wrong... The overloaded << if I make it into an inline function. But how do I make it work in my case? warning: friend declaration std::ostream& operator<<(std::ostream&, const D<classT>&)' declares a non-template function warning: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) -Wno-non-template-friend disables this warning /tmp/cc6VTWdv.o:uppgift4.cc:(.text+0x180): undefined reference to operator<<(std::basic_ostream<char, std::char_traits<char> >&, D<int> const&)' collect2: ld returned 1 exit status template <class T> T my_max(T a, T b) { if(a > b) return a; else return b; } template <class classT> class D { public: D(classT in) : d(in) {}; bool operator>(const D& rhs) const; classT operator=(const D<classT>& rhs); friend ostream& operator<< (ostream & os, const D<classT>& rhs); private: classT d; }; int main() { int i1 = 1; int i2 = 2; D<int> d1(i1); D<int> d2(i2); cout << my_max(d1,d2) << endl; return 0; } template <class classT> ostream& operator<<(ostream &os, const D<classT>& rhs) { os << rhs.d; return os; }

    Read the article

  • C++ Array Initialization in Function Call or Constructor Call

    - by david
    This question is related to the post here. Is it possible to initialize an array in a function call or constructor call? For example, class foo's constructor wants an array of size 3, so I want to call foo( { 0, 0, 0 } ). I've tried this, and it does not work. I'd like to be able to initialize objects of type foo in other objects' constructor initialization lists, or initialize foo's without first creating a separate array. Is this possible?

    Read the article

  • Java constructor with large arguments or Java bean getter/setter approach

    - by deelo55
    Hi, I can't decide which approach is better for creating objects with a large number of fields (10+) (all mandatory) the constructor approach of the getter/setter. Constructor at least you enforce that all the fields are set. Java Beans easier to see which variables are being set instead of a huge list. The builder pattern DOES NOT seem suitable here as all the fields are mandatory and the builder requires you put all mandatory parameters in the builder constructor. Thanks, D

    Read the article

  • Accessing constructor from abstract base class with reflection

    - by craesh
    Hi! I'm playing around with Java's Reflection. I have an abstract class Base with a constructor. abstract class Base { public Base( String foo ) { // do some magic } } I have some further classes extending Base. They don't contain much logic. I want to instantiate them with Base's constructor, without having to write some proxy contructors in those derived classes. And of course, I want to instantiate those derived classes with Reflection. Say: Class cls = SomeDerivedClass.class; Constructor constr; constr = cls.getConstructor( new Class[] { String.class } ); // will return null Class clsBase = Base.class; constr = clsBase.getConstructor( new Class[] { String.class } ); // ok Base obj = (Base) constr.newInstance( new Object[] { "foo" } ); // will throw InstantiationException because it belongs to an abstract class Any ideas, how I can instantiate a derived class with Base's constructor? Or must I declare those dumb proxy constructors?

    Read the article

  • Can a single argument constructor with a default value be subject to implicit type conversion

    - by Richard
    I understand the use of the explicit keyword to avoid the implicit type conversions that can occur with a single argument constructor, or with a constructor that has multiple arguments of which only the first does not have a default value. However, I was wondering, does a single argument constructor with a default value behave the same as one without a default value when it comes to implicit conversions?

    Read the article

  • Good style for handling constructor failure of critical object

    - by mtlphil
    I'm trying to decide between two ways of instantiating an object & handling any constructor exceptions for an object that is critical to my program, i.e. if construction fails the program can't continue. I have a class SimpleMIDIOut that wraps basic Win32 MIDI functions. It will open a MIDI device in the constructor and close it in the destructor. It will throw an exception inherited from std::exception in the constructor if the MIDI device cannot be opened. Which of the following ways of catching constructor exceptions for this object would be more in line with C++ best practices Method 1 - Stack allocated object, only in scope inside try block #include <iostream> #include "simplemidiout.h" int main() { try { SimpleMIDIOut myOut; //constructor will throw if MIDI device cannot be opened myOut.PlayNote(60,100); //..... //myOut goes out of scope outside this block //so basically the whole program has to be inside //this block. //On the plus side, it's on the stack so //destructor that handles object cleanup //is called automatically, more inline with RAII idiom? } catch(const std::exception& e) { std::cout << e.what() << std::endl; std::cin.ignore(); return 1; } std::cin.ignore(); return 0; } Method 2 - Pointer to object, heap allocated, nicer structured code? #include <iostream> #include "simplemidiout.h" int main() { SimpleMIDIOut *myOut; try { myOut = new SimpleMIDIOut(); } catch(const std::exception& e) { std::cout << e.what() << std::endl; delete myOut; return 1; } myOut->PlayNote(60,100); std::cin.ignore(); delete myOut; return 0; } I like the look of the code in Method 2 better, don't have to jam my whole program into a try block, but Method 1 creates the object on the stack so C++ manages the object's life time, which is more in tune with RAII philosophy isn't it? I'm still a novice at this so any feedback on the above is much appreciated. If there's an even better way to check for/handle constructor failure in a siatuation like this please let me know.

    Read the article

  • Getting the instance when Constructor#newInstance throws?

    - by Shtééf
    I'm working on a simple plugin system, where third party plugins implement a Plugin interface. A directory of JARs is scanned, and the implementing classes are instantiated with Constructor#newInstance. The thing is, these plugins call back into register* methods of the plugin host. These registrations use the Plugin instance as a handle. My problem is how to clean up these registrations if the constructor decides to fail and throw halfway through. InvocationTargetException doesn't seem to have anything on it to get the instance. Is there a way to get at the instance of an exception throwing constructor? P.S.: It's typically strongly advised to users that the constructor not do anything, but in practice people are doing it any ways.

    Read the article

  • Function template overloading: link error

    - by matt
    I'm trying to overload a "display" method as follows: template <typename T> void imShow(T* img, int ImgW, int ImgH); template <typename T1, typename T2> void imShow(T1* img1, T2* img2, int ImgW, int ImgH); I am then calling the template with unsigned char* im1 and char* im2: imShow(im1, im2, ImgW, ImgH); This compiles fine, but i get a link error "unresolved external symbol" for: imShow<unsigned char,char>(unsigned char *,char *,int,int) I don't understand what I did wrong!

    Read the article

  • Overloading new, delete in C++

    - by user265260
    i came across this line is stroustrup An operator function must either be a member or take at least one argument of a user-defined type (functions redefining the new and delete operators need not). Dont operator new and operator delete take an user defined type as one of their arguments? what does it mean, am i missing something here

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >