Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,859 questions

51,780 answers

573 users

How to use struct with methods and constructor in C++

4 Answers

0 votes
#include <iostream>

using namespace std;
 
struct ST {
  int num;
  ST() : num(845) {} // constructor
  int get_num() { 
      return num; 
  }
};


int main () {
    ST s;
    cout << s.get_num();

    return 0;
}



/*
run:
 
845
 
*/

 



answered Nov 13, 2019 by avibootz
0 votes
#include <iostream>

using namespace std;
 
struct ST {
  int num;
  ST() {} // constructor
  int get_num() { 
      return num; 
  }
};


int main () {
    ST s;
    cout << s.get_num();

    return 0;
}



/*
run:
 
32767
 
*/

 



answered Nov 13, 2019 by avibootz
0 votes
#include <iostream>

using namespace std;
 
struct ST {
  int num;
  int get_num() { 
      return num; 
  }
  void set_num(int n) { 
      num = n; 
  }
};


int main () {
    ST s;
    
    s.set_num(999);
    
    cout << s.get_num();

    return 0;
}



/*
run:
 
999
 
*/

 



answered Nov 13, 2019 by avibootz
0 votes
#include <iostream>

using namespace std;
 
struct ST {
  int num;
  ST(int n) : num(n) {} // constructor
  int get_num() { 
      return num; 
  }
  void set_num(int n) { 
      num = n; 
  }
};


int main () {
    ST s(8271);

    cout << s.get_num();

    return 0;
}



/*
run:
 
8271
 
*/

 



answered Nov 13, 2019 by avibootz

Related questions

1 answer 120 views
1 answer 136 views
1 answer 158 views
2 answers 145 views
2 answers 192 views
1 answer 126 views
...